C ++读取文本文件中的所有行 [英] C++ read all lines in text file

查看:112
本文介绍了C ++读取文本文件中的所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在mfc项目中获得了所有10行(逐行)作为CStringArray,但是收到第4行字符串的错误。



我的文本文件是:



C:\程序文件(x86)\ GRETECH \ GOMPlayer \ GOM.EXE

C:\ Program Program \视频LAN \ VLC \ vlc.exe

C:\Program Files(x86)\ Google + \\ Chrome \ Application \ chrome.exe

C:\ Windows \\\
otepad.exe

C:\ Windows \System32 \ cmd.exe

C:\ Windows \ System32 \ mspaint .exe

C:\ Windows \ System32 \ calc.exe

C:\ Windows \ System32 \ calc.exe

C:\ Windows \ System32 \ osk.exe

C:\ Windows \ System32 \ msconfig.exe



请检查我的功能或替代此功能。并请为我的代码更新任何一行。



我尝试过:



I am getting all 10 lines (line by line ) in mfc project as CStringArray but recieve error on to getting 4th line string.

my text file is:

C:\Program Files (x86)\GRETECH\GOMPlayer\GOM.EXE
C:\Program Files\VideoLAN\VLC\vlc.exe
C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
C:\Windows\notepad.exe
C:\Windows\System32\cmd.exe
C:\Windows\System32\mspaint.exe
C:\Windows\System32\calc.exe
C:\Windows\System32\calc.exe
C:\Windows\System32\osk.exe
C:\Windows\System32\msconfig.exe

Please check my function or alternate to this function. And please code me fuction for updating any line.

What I have tried:

    CString AMyClass::getStringfromText(CString filename, int linenumber)
    {
    CStdioFile file;	
    CStringArray aLineArray;
    CString All_Lines;
    CString out;
    CString strExePath;
    
    linenumber=linenumber-1;
    CString applicationPath;
    char fname[_MAX_PATH+1];
    
    ::GetModuleFileNameA(NULL,fname,_MAX_PATH);
    applicationPath = fname;
    applicationPath.MakeLower();
    strExePath = applicationPath.Left(applicationPath.ReverseFind('\\') + 1);

    file.Open(strExePath+filename, CFile::modeRead);

    while (file.ReadString(All_Lines))
    {
    aLineArray.Add(All_Lines);

    }
    file.Close ();
    out=aLineArray[linenumber];
    return out;
    }

**and code is:**

    CString str_s4;
    str_s4=AMyClass::getStringfromText (_T("MyApps.ini"),4);
    AfxMessageBox(str_s4);

推荐答案

您应该使用调试器并进入代码。我想从阅读中找到的文件在目录中找不到,所以aLineArray是空的。



良好的编码意味着还要检查文件等功能。打开并出现一些错误处理:

You should use the debugger and step into the code. I guess from reading that the the file wasnt found in the directory and so the aLineArray is empty.

Good coding means also checking functions like the file.Open and some error handling:
if( !file.Open(strExePath+filename, CFile::modeRead) ) {
  TRACE("File couldnt get opened");
  return "";
}


这篇关于C ++读取文本文件中的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆