I am trying to learn C and the book I am using (Apress’ ‘Learn C’) has a chapter that is terribly confusing on Random Access functions. The following code is confusing me:
int GetNumberOfDinos( void ) {
FILE *fp;
long fileLength;
if ( (fp = fopen( kDinoFileName, "r" )) == NULL )
DoError( "Couldn't open file...Goodbye!" );
if ( fseek( fp, 0L, SEEK_END ) != 0 )
DoError( "Couldn't seek to end of file...Goodbye!" );
if ( (fileLength = ftell( fp )) == -1L )
DoError( "ftell() failed...Goodbye!" );
fclose( fp );
return( (int)(fileLength / kDinoRecordSize) );
}
I understand the purpose of the code, but not how that purpose is being achieved. The fopen line is easy to understand. The fseek and ftell is where my troubles begin. The parameters for fseek are the file, the offset, and then one of the 3 SEEKs. Why is the condition of it not being zero given there? If the file truly does exist (kDinoFileName), and they want to point to the end of that file, why would the location be zero? The file exists and there is information! And then I completely don’t understand how the ftell function would ever end up with -1L?? Is this code more difficult than it needs to be?
The code is simply checking for errors.
fseek()returns 0 on success and non-zero on failure.ftell()returns -1 on failure.As far as “why would the location be zero?” – the
fseek()call is requesting to seek from the end of the file (SEEK_END). Zero bytes from the end of the file is.. the end of the file. Sois a request to move the file pointer to the end of the file.
The code is performing the following steps:
The code is complicated somewhat by the error handling. Many books and articles leave out the error handling for exactly that reason. However, that has it’s own drawback of teaching people to ignore error conditions.