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.
#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()
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]This site is dead. Check out my new web site A Funkaoshi Production.
A simple blog of sorts. Updated sporadically at best. Here you will find my opinions on various topics of interest to me, or the goings on of my day. Yes, it's quite exciting I know.
Next: The Complete Faye Wong Discography