C++文件操作——按行读取txt文本文件
我们经常在一些项目中需要处理文本文件的读取,比如按行进行文本读取操作
下面分别介绍按行读取文本的一些方法:
(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 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 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 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();
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
