Fin.good()

Hi folks,

what is wrong with the following SHORT program ?

I compile it on RedHat 9 with g++

///// start

#include “fstream”
#include “iostream”
using namespace std;

int main()
{

// tries to open non-existing file ( does not find it of course)
// creates the file
// tries to open the created file
// DOES NOT WORK !!!

string filename(“crap.txt”);
ifstream fin;
fin.open(filename.c_str());
if(fin.good()) cout << “Opened existing file " << filename << endl;
else
{
fin.close();
ofstream fout;
fout.open(filename.c_str());
fout << " crap” << endl;
fout.close();

fin.open(filename.c_str());
if(fin.good())
{
cout << " Created and Opened file " << filename << endl;
}
else
{
cout << " ERROR " << endl;
cout << " fin.good() returns false despite existing file" << endl;
}

}

return 0;
}
testIFSTREAM.cxx (660 Bytes)

Add the statement

after closing fin the first time, so as to clear the failure when
first trying to open the file. Alternatively, use is_open()
instead of good(), which would seem more logical for what
you are trying to check for.

Regards,
Gora