Subscribe to #define's Blog        RSS Feed
-----

A quick look at reading, all the data until the end of the file. In C++ using the input file stream.

Icon Leave Comment
Assuming a filestream fstrm say :

ifstream fstrm;


Probably most learners would do some such thing :

while( !fstrm.eof() )
{
  fstrm >> variable;
  cout << variable << endl;
}



This works upto a point, but there can be problems.
This doesn't handle a failed read, eg. when trying to read a number you get a character.
This doesn't handle a bad read, eg. when the file isn't open, or the OS cannot read the file properly.
This doesn't handle whitespace near the end of the file (not considered here, but handled by fail later).

To handle these problems we could try this

while( !fstrm.eof() && !fstrm.fail() && !fstrm.bad() )
{
  fstrm >> variable;
  cout << variable << endl;
}



This while expression can be simplified to
while( fstrm.good() )
{
  fstrm >> variable;
  cout << variable << endl;
}



There can still be a problem because the variable is read and the data processed without checking the stream.
The stream and integrity of the data can be checked like so:-

while( fstrm.good() )
{
  fstrm >> variable;
  if( fstrm.good() )
  {
    cout << variable << endl;
  }
}



The read can work in an if expression and the code will work in the same way. *
while( fstrm.good() )
{
  if( fstrm >> variable )
  {
    cout << variable << endl;
  }
}




If the read can work in an if expression it can also work in a while expression.
while( fstrm >> variable )
{
  cout << variable << endl;
}



Here any whitespace at the end of the file is handled because the read will fail without data.


* Not sure but older compilers may have a problem here.

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

February 2020

S M T W T F S
      1
2345678
9101112131415
16171819202122
23 242526272829

Tags

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)

Categories