MFC-按行读取TXT数据

 

TXT中数据格式如下:

1

23

4

0

4

10

……

 

要实现的功能是:定义一个函数,每次调用时从TXT文档中读一个整数 ,赋值给变量。同时,文件位置向下移动一行,以便下次调用时读取下一行的数据。

 

MFC主要读写文件的类是CFile,CStdioFile类是派生自CFile类的,主要增加了一个按行的方式读取/写入文件每行字符串的功能【读写TXT文件,写入和输出必须统一格式】。所以实现按行读取字符串用CStdioFile类。

 

代码:

void CMFCdemoDlg::getPersonCnt()
{
    CStdioFile file;
    CString strText=_T("");

    if (file.Open(_T("E:\count.txt"), CFile::modeRead))
    {
        
        file.Seek(pos, CFile::begin);

        if (file.ReadString(strText))
        {
            pos = file.GetPosition();//记录读到了哪一行;
            m_personCount = _ttoi(strText);
            SetDlgItemInt(IDC_PERSONCOUNT_EDIT,m_personCount);
        }
        else
        {
            SetDlgItemText(IDC_PERSONCOUNT_EDIT, _T("读入错误"));
        }
        file.Close();
    }

}

 

 注:pos(DWORD)与m_personCount(int)是对话框类的数据成员。

 

 

参考:https://bbs.csdn.net/topics/340105743

https://blog.csdn.net/zollll/article/details/54861253

 

 

原文地址:https://www.cnblogs.com/Tang-tangt/p/9525947.html