Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why read file first then check?

Tags:

c++

iostream

I'm just revising for my exams and can't get my head around the following provided by our lecturer:

When opening fstreams, check if you have opened or not

  • Then read before check for input_file.fail()

  • If you check before read, you may end up with an extra unwanted input

It doesn't make sense to me to read first, shouldn't you check first?

If anyone is able to explain, I would be very grateful :)

like image 951
jewfro Avatar asked Jun 19 '13 22:06

jewfro


1 Answers

input_file.fail() determines if any preceding operations have failed, not whether the upcoming operation is going to fail. Consequently, if you write this:

if (!input_file.fail()) {
    int value;
    input_file >> value;

    /* ... process value ... */
}

Then after reading value, you have no idea whatsoever whether you actually read anything successfully or not. All you know is that right before you did the read, everything was working correctly. It's quite possible that you failed to read an integer, either because you hit the end of the file, or the data in the file wasn't an integer.

On the other hand, if you write

int value;
input_file >> value;

if (!input_file.fail()) {
    /* ... process value ... */
}

Then you attempt to do a read. If it succeeds, you then process the value you've read. If not, you can then react to the fact that the last operation failed.

(You can be even cuter than this:

int value;
if (input_file >> value) {
    /* ... process value ... */
}

which combines the read and test operations into one. It's much clearer here that you're confirming that the read succeeded.)

If you're doing reads in a loop, a very clean way to do this is

for (int value; input_file >> value; ) {
   /* ... process value ... */
}

This makes clear that you loop while you're able to keep reading values from the file.

Hope this helps!

like image 58
templatetypedef Avatar answered Sep 24 '22 21:09

templatetypedef