C++ not reading anything from files

124 views Asked by At

I seem to be having a problem reading files. I am using Visual Studio Community 2013 and it will do everything but reading of files. I have checked to make sure the file being read and written is in the same directory. The following code is where I believe the problem to be:

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;
}

and I get the "This file is royally jacked up" result. I don't understand why it's not reading. Please help.

3

There are 3 answers

2
R Sahu On BEST ANSWER

Change the lines:

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())

to

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())

You don't want to call open on a valid ifstream.

Here's a sample program that demonstrates that calling open on a valid ifstream can make it invalid.

#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;
}

Output:

ifstream is good.
ifstream is not good any more.
2
user35443 On

It might help to use clear before opening a new file, as open may not clear the flags on its own.

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

You could also use is_open instead of good.

if(inStream.is_open()) {
    ...
1
js sol On

Try calling inStream.clear() before doing anything with it. clear() clears the old flags like bad being true.