Search code examples
cfilepointerseoffseek

Why is my program perceiving an EOF condition way before my file actually ends?


My code reads line by line from a text file and stores the lines in a massive array of char pointers. When I use an ordinary text file, this works with no issues. However, when I try to read from the 'dictionary.txt' file I'm supposed to be using, my program detects EOF after reading the first of MANY lines in the file.

int i = 0;
while( 1 ) {
    
    size_t size = 50;
    fseek( dicFile, 0L, getline( &dictionary[i++], &size, dicFile) ); 
    printf( "%d:\t%s", i, dictionary[i - 1] );
    
    if( feof( dicFile ) ) {  
            fclose( dicFile );
            break;  
    }
    
}
puts("finished loading dictionary");

Here is the start of the dictionary file I'm attempting to load:

A
A's
AA's
AB's
ABM's
AC's
ACTH's
AI's
AIDS's
AM's
AOL
AOL's
ASCII's
ASL's
ATM's
ATP's
AWOL's
AZ's

The output is get from this portion of the program is:

1:  A
2:  finished loading dictionary

Thanks for any help.


Solution

  • Your third argument to fseek() is nuts. I've seen at least one implementation that treated every out of range third argument as SEEK_END. Oops.

    You should just call getline() in the loop instead. In fact, just check the return value of getline() for -1 and get rid of that feof().