【问题标题】:ifstream is failing to open my fileifstream 无法打开我的文件
【发布时间】:2015-03-18 00:05:55
【问题描述】:

我正在创建一个使用来自简单文本文件的信息的程序。但是,它每次都会被我的 .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;

    }

【问题讨论】:

  • 据我所知?如果这就是你的意思,我不会有任何错误
  • 您是否尝试过打印出fileNameIn.c_str() 来检查它是不是您认为的那样?
  • 输出失败语句时文件名是否正确(没有任何多余的空格)?
  • 正常的调试技术是对已知的东西进行硬编码以排除一段代码有问题。
  • @user657267 几乎所有其他时间,filename 变量不包含发帖人声称的字符串。

标签: c++ file ifstream


【解决方案1】:

试试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 good Returns true if none of the stream's error state flags (eofbit, failbit and badbit) is set.

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

【讨论】:

  • ifstream总是in 添加到传递给 filebuf 构造函数的标志列表中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-18
相关资源
最近更新 更多