On 2011-02-07 "Paul" <pchristor@yahoo.co.uk> wrote:
It depends on the purpose of the program, how critical it is and
how much control you want.
I start writing C++ programs and I want to start with a good
programming style from the scratch.
The problem with both your programs is that you check incase the
file handle is null , but you don't abort if it is.
It's not a problem. For demonstration I removed everything that is
not really necessary to understand my problem. I abort if the file
is not found in the real program.
If you use a simple 'if' statement then you should construct your
code in such a way that...
if(filehandle is good){ do stuff}
else{ output error and abort }
It depends on the purpose and how critical your program is. If you
are just creating small test porgrams then its fine to not bother
with error checking at all. I like to always wrap file ops in an
if statement, even in trivial programs, as I think its good
practise. I'd actually put file ops inside a function and do
something like:
if(filehandle) { fileOpsFunction( filehandle); }
It keeps your main() function cleaner and easier to read. I put
almost everything in functions. :)
It is included in a function. I just removed all unnecessary stuff
to make the code as easy as possible.
But one question is still open: Is it possible to do something like:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
ifstream fileIn;
fileIn.exceptions ( ifstream::failbit | ifstream::badbit );
try {
fileIn.open( "file" ); }
catch ( ifstream::failure e ) {
cout << "Error."; }
fileIn.exceptions ( none ); // Switch exceptions off
string line;
while ( getline( fileIn, line ) ) {
cout << line << endl;
}
fileIn.close();
return 0;
}
I mean to switch the exceptions off again after having switched
them on before to avoid that the while loop is able to throw an
exception?
the kind you try to catch. Open() returns NULL if it cannot open the
file (which is not considered exceptional).
out of memory. In that case, writing to std::cout is likely not to
work either (perhaps causing another bad_alloc). :-(