ifstream无法打开我的文件

ifstream is failing to open my file

本文关键字:我的 文件 ifstream      更新时间:2023-10-16

我正在创建一个使用简单文本文件中信息的程序。然而,它每次都会被我的.fail()函数捕获。该文件名为Test.txt,与程序的.exe文件位于同一文件夹中。我不知道为什么它一直在点击.fail()

以下是我创建ifstream、打开文件和.fail()循环的代码。

ifstream input;
    input.open(fileNameIn.c_str());
    if(input.fail()){
        cout << "File named " << fileNameIn << " did not open successfully."     << endl;
    }

尝试input.open(strSourceFile.c_str(), std::ifstream::in);,看看这是否有帮助。

这是我使用c++读取文件时使用的模式

//
// FileAccessor is just my wrapper around ifstream
// inside the constuctor: 
//    ifstream.open(strSourceFile.c_str(),std::ifstream::in); is called
//
FileAccessor fileAccessor(textFile);
while(fileAccessor.good()) {
    fileAccessor.getline(lineOfText);
    ...
    if(fileAccessor.eof()) break;
}

根据http://www.cplusplus.com/reference/ios/ios/good/bool good() const;

Check whether state of stream is goodReturns true if none of the stream's error state flags (eofbit, failbit and badbit) is set.

您可以在循环中设置一个标志,看看它是否进入过循环,如果没有,则检查错误位标志。