C ++没有从文件中读取任何内容

时间:2015-06-10 04:47:22

标签: c++ io

我似乎在阅读文件时遇到了问题。我正在使用Visual Studio社区2013,除了阅读文件外,它将执行所有操作。我已检查以确保正在读取和写入的文件位于同一目录中。以下代码是我认为问题所在:

if (inStream.bad())
{
    inStream.close();

    outStream.open(filename);
    outStream << "This is a test file: \nWelcome to the Dark Side!";
    outStream.close();
}

inStream.open(filename, ios::in);
if (inStream.good())
{
    while (getline(inStream, stream[1]))
    {
        stream[0] += stream[1] + '\n';
    }

    inStream.close();

}
else
{
    cout << "THIS FILE IS ROYALLY *jacked* UP!!!!" << endl;
}

然后我得到了#34;这个文件被皇家提升了#34;结果。我不明白为什么它不读书。请帮忙。

3 个答案:

答案 0 :(得分:0)

在打开新文件之前使用clear可能会有所帮助,因为open可能无法自行清除标记。

inStream.clear();
inStream.open(filename, ios::in);

您也可以使用is_open代替good

if(inStream.is_open()) {
    ...

答案 1 :(得分:0)

在对它做任何事情之前尝试调用inStream.clear()。 clear()清除旧标志,就像坏事一样。

答案 2 :(得分:0)

更改行:

if (inStream.bad())
{
    inStream.close();

    outStream.open(filename);
    outStream << "This is a test file: \nWelcome to the Dark Side!";
    outStream.close();
}

inStream.open(filename, ios::in);
if (inStream.good())

if (inStream.bad())
{
    inStream.close();

    outStream.open(filename);
    outStream << "This is a test file: \nWelcome to the Dark Side!";
    outStream.close();

    // Clear the state of the stream.
    inStream.clear();

    // Move this line inside the block.
    inStream.open(filename, ios::in);
}

if (inStream.good())

您不想在有效的open上致电ifstream

这是一个示例程序,用于演示在有效open上调用ifstream会使其无效。

#include <iostream>
#include <fstream>

int main()
{
   std::ifstream inFile("socc.in");
   if ( inFile.good() )
   {
      std::cout << "ifstream is good.\n";
   }

   inFile.open("socc.in");
   if ( inFile.good() )
   {
      std::cout << "ifstream is still good.\n";
   }
   else
   {
      std::cout << "ifstream is not good any more.\n";
   }

   return 0;
}

输出:

ifstream is good.
ifstream is not good any more.