Search code examples
cfilescanffeof

Reading unknown number of integers from a file


This is a function that reads an unknown number of integers from a file and calculates the average. For some reason the last element in the file is being read twice. Can someone please explain why? I know how to fix it but would like to know what goes on behind the scenes.

int total = 0, count = 0, input;
FILE *filePtr;

filePtr = fopen("file.txt", "r");
if (filePtr != NULL)
    do
    {
        fscanf(filePtr, "%d", &input);
        total = total + input;
        count++;
    } while (!feof(filePtr));

printf ("%d", total);

I fixed it by putting a second if in the loop:

    do
    {
        fscanf(filePtr, "%d", &input);
        if (!feof(filePtr))
        {
            total = total + input;
            count++;
        }
    } while (!feof(filePtr));

Solution

  • You're not checking that fscanf actually finds a number. The last call will fail because you're most likely just reading in the last line break in the file.

    Try this:

    do
    {
        if (fscanf(filePtr, "%d", &input)==1) {
            total = total + input;
            count++;
        }
    } while (!feof(filePtr));
    

    EDIT: @Andrew is right — you should really check for an EOF at the top of the loop:

    while (!feof(filePtr)) {
        /* ... */
    }