fscanf() returns the same pattern in a loop

The fscanf function in the following code matches the same pattern over and over again in a file, rather than moving on to the next one. How can I fix this?

void checkInput(char *fileName, int time, int* totalProcesses)
{
    FILE *input;
    int startTime;
    int pid;
    int prio;    
    int vruntime = 50;
    input = fopen(fileName, "r");

    do
    {
        fscanf(input, "%i start %i prio %i", &pid, &startTime, &prio);

        if(startTime == time)
        {
            createProcess(pid, startTime, vruntime);
            totalProcesses++;
            printf("%s\n %i", "proccess created", pid );
        }   

    } while ( !feof(input) );

    fclose(input);
}

1 answer

  • answered 2017-11-12 20:59 Chris Dodd

    Check the return value of fscanf -- when it fails it doesn't read anything, so if you loop and try it again, the same thing will happen. Instead you need something like:

    while(fscanf(input, "%i start %i prio %i", &pid, &startTime, &prio) == 3) {
        if(startTime == time) {
            createProcess(pid, startTime, vruntime);
            totalProcesses++;
            printf("%s\n %i", "proccess created", pid );
        }
    }
    

    This also means you don't use feof