I want to read a file which contains a list of integers. The first 4 bytes( or whatever sizeof(int) is ) indicates how many numbers the file has.
Suppose I check the file size before reading so that I know I won't encounter EOF. Do I still need to check for file read errors? Is yes, why and what would be the correct way to do it (i.e. check after each read or once at the end )
istream fin;
fin = open( "input.num", ios::in );
if( !fin )
... // Error
fin.seekg( 0, ios::end ) // Find file size
fileSize = fin.tellg( );
if( fileSize < sizeof( int )) // Need atleast one int
...// Error
fin.seekg( 0, ios::beg );
fin<<count; // First int tells the number of ints in the file
// if( fin.bad( )) // Check here too?
if( fileSize != (count+1)*sizeof(int)) // Verify file size
...// Error
for( i = 0; i < count; i++ )
{
fin<<numbers[i];
// if( fin.bad( )) // Or shoud I use fin.fail( )? It wont be EOF
// // Should this be checked each time?
...// Error
}
// if( fin.fail( )) // Or check error only once after reading?
... // Error
...
Does the same thing apply to writing to a file?