why ofstream function is_open() return true after open a nonexistent file?

Please help... any suggestions? I'm trying to make my program robust by checking for errors using member function .is_open()
but it just doesn't seem to want to work today for some reason.


void promptfiles(string & infile, string & outfile)
{
do{
cout << "Which file do you want to encrypt? " << endl;
cin >> infile;
cout << endl << "Which file will you be saving it to? (caution may overwrite files if not careful) " << endl;
cin >> outfile;
}while(!check_files(infile, outfile));
}


bool check_files(string & infile, string & outfile)
{
bool good = true, bad = false;
ifstream fint; fint.close(); fint.clear(); fint.open(infile.c_str());
ofstream fout; fout.close(); fout.clear(); fout.open(outfile.c_str());

if (fout.is_open()) cout << "OMG the world is coming to an end!!! " << endl;

if ( (!fint.is_open()) || (fout.is_open()))
{
if (!fint.is_open())
cout << "Input file does not exist. Try harder next time. " << endl;
if (fout.is_open())
cout << "Output file already exists. Don't do that. " << endl;
return bad;
}

return good;
}
Because opening a file for output creates an empty file if one doesn't exist. std::ofstream::is_open() will only return false if the file couldn't be created (e.g. because the file system is full or read-only).

EDIT: Some compilers let you pass a flag to the constructor or to open() that won't create an empty file, but this isn't standard.
Last edited on
ofstream::open will create the file if it doesn't exist

[edit] too late...
Last edited on
never mind

i get so frustrated sometimes I overlook the obvious...
Last edited on
Topic archived. No new replies allowed.