1

I am pretty new to C and have a very simple function for displaying file contents here. It works fine, except the last line of my file prints twice...I know that it has to do w/EOF but I can't figure out how to get the function to recognize EOF as the last line and not run once more. I know there are a billion places on the internet with similar issues, but lots were for C++ and since I am new I thought it would be best to just use my own code. Here is the code:

 {
    int count=0, fileEnd=0;

    FILE* rockPtr=fopen("rockact.txt", "r");

    printf("\n%8s%8s%8s%8s%8s\n", "BANDID", "NAME", "SIZE", "CREW", "TRANS");

    do
    {
        fileEnd=fscanf(rockPtr, "%d%s%d%d%s", &(tempBand.rockid), tempBand.bandname, &(tempBand.bandsize), &(tempBand.crewsize), tempBand.transport);
            if (fileEnd !=EOF); //checks EOF has not been reached
            {
                printf("\n%8d%8s%8d%8d%8s", tempBand.rockid, tempBand.bandname, tempBand.bandsize, tempBand.crewsize, tempBand.transport);
                count++;                
            }               
    }
    while (fileEnd !=EOF);

    fclose(rockPtr);
    printf("\n The total amount of rock acts on file is %d\n", count);
    }
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
user2884601
  • 13
  • 1
  • 6

2 Answers2

4

Your if condition doesn't want the semi-colon:

  if (fileEnd !=EOF); // This semicolon is wrong!

The semicolon is a null statement and is the body of the if.

I'd rather see the whole loop cast as a while loop:

while (fscanf(rockPtr, "%d%s%d%d%s", &tempBand.rockid, tempBand.bandname,
              &tempBand.bandsize, &tempBand.crewsize, tempBand.transport)) == 5)
{
    printf("\n%8d%8s%8d%8d%8s", tempBand.rockid, tempBand.bandname,
           tempBand.bandsize, tempBand.crewsize, tempBand.transport);
    count++;                
}

If you want to worry about it, you can spot the difference between EOF, read error and format error after the loop. Note that the check is that all values were converted OK.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
1

you have ; after if - remove it

also, check manual for fscanf

If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned.

This mean that you can read at least partial data from file, reach EOF or error, but fscanf will not return it.

You should use feof function to check whether end of file is reached

so your logic should be:

  1. read from file
  2. if anything is read - display it, here I mean you should compare returned number with count of arguments, not with EOF
  3. check for feof

UPDATE: during opening/reading from file you should always check ferror, as EOF is not the only problem

Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57