January 15, 2004 06:53 PM C++ is an Odd Beast

File I/O with C++ is dodgy at best, though it is much better then the hoops you have to jump through to get Java to read a text file. My problem right now is that if I point an input stream at a non-existent file it does't complain.

in = new ifstream(argv[1]);
if (in->bad())
{ printErrorMsg("Can't open input file for reading");
}

I expect that if argv[1] is the filename of a file that does not exist that in->bad() would return true. Shame that it doesn't.

Comments on C++ is an Odd Beast

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int
main( int argc, char * argv[] )
{
    if( argc > 1 && argv[ 1 ] ) {
        ifstream inFile( argv[ 1 ] );

        if( inFile ) {
            string      firstLine;

            getline( inFile, firstLine );
            cout << argv[ 1 ] << " was opened okay. "
                 << "The first line of the file is: " << endl
                 << firstLine << endl;
        } else {
            cout << argv[ 1 ] << " was not opened" << endl;
        } // if
    } else {
        cout << "Usage: " << argv[ 0 ] << " <filename>" << endl;
    } // if

    return 0;
} // main()        

[Posted by Ryan on January 15, 2004 07:32 PM]

Probably it only becomes bad() after it encounters failure reading something. The above code works. :-)

[Posted by Ryan on January 15, 2004 07:34 PM]

Yeah. It works if I replace the bad call with !(*in). Good work Ryan.

[Posted by ramanan on January 15, 2004 07:35 PM]
Don't copy me without asking.     moveable type     1and1     XHTML     XFN     CSS.     ramanan at funkaoshi dot com.