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?