C++文件操作——按行读取txt文本文件

来源:互联网 发布:get是什么意思网络上的 编辑:程序博客网 时间:2024/06/05 23:05

我们经常在一些项目中需要处理文本文件的读取,比如按行进行文本读取操作

下面分别介绍按行读取文本的一些方法:

(1).采用C语言中的fgets函数

USES_CONVERSION;  //调用函数,T2A和W2A均支持ATL和MFC中的字符转换  char * pLogPath = T2A(fileDlg.GetPathName());  FILE *fp = fopen(pLogPath, "r");  if(NULL == fp)  {       AfxMessageBox(L"failed to open txt\n");       return;}  vector<string> v_str;string strShow;while(!feof(fp))  {      char szLineBuffer[MAX_PATH]="";    fgets(szLineBuffer, sizeof(szLineBuffer)-1, fp); // 包含了\n      v_str.push_back(szLineBuffer);     strShow += szLineBuffer;    strShow += "\r\n";    USES_CONVERSION;     CString cstrShow(strShow.c_str());      m_CtrlEditRead.SetWindowText(cstrShow);} fclose(fp);  
(2).C++中ifstream流getline函数获取

USES_CONVERSION;  //调用函数,T2A和W2A均支持ATL和MFC中的字符转换  char * pLogPath = T2A(fileDlg.GetPathName()); ifstream inFile(pLogPath);vector<string> v_str;string strShow;if (inFile){    string strLine;    while(getline(inFile, strLine)) // line中不包括每行的换行符     {         v_str.push_back(strLine);      strShow += strLine;      strShow += "\r\n";      USES_CONVERSION;       CString cstrShow(strShow.c_str());        m_CtrlEditRead.SetWindowText(cstrShow);   }  }
(3).MFC中CStdioFile类ReadString按行读取

vector<CString> v_cstr;CStdioFile file;if (file.Open(fileDlg.GetPathName(), CFile::typeText | CFile::modeRead)){CString str;// 处理UNICODE下【中文乱码】异常char * pOldLocale = _strdup(setlocale(LC_CTYPE, NULL));setlocale(LC_CTYPE, "chs");CString strShow;while (file.ReadString(str)){v_cstr.push_back(str);strShow += str;strShow += "\r\n";m_CtrlEditRead.SetWindowText(strShow);str.Empty();}// 处理完毕后,释放资源setlocale(LC_CTYPE, pOldLocale);free(pOldLocale);}file.Close();

阅读全文
0 0
原创粉丝点击