-1

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);
}
Hamza
  • 1
  • Please read on how to produce a proper [mcve]. Perhaps you should also check the return value of `fscanf`. An example of the input in `fileName` could be nice as well... – Antti Haapala -- Слава Україні Nov 12 '17 at 19:48
  • Note that if your code runs into a problem because, for example, a colon turns up in the time field, or `start` is misspelled once, or something similar, you will repeatedly fail at the same point in the processing. You must check the return value from `fscanf()`. If it fails with a return value of 0, 1, or 2, then you can consider reading to the end of line before trying again. If you use line-based input (`fgets()`) and then `sscanf()`, you can print what is causing the trouble. It's much harder to do that when `fscanf()` has consumed some of it. – Jonathan Leffler Nov 12 '17 at 22:51
  • See also [`while (!feof(file))` is always wrong](https://stackoverflow.com/questions/5431941/) — and this code is no exception. – Jonathan Leffler Nov 12 '17 at 22:52
  • @Stargateur: only 3 `scanf()` conversion specifiers do _not_ skip leading white space: `%c`, `%[…]` (scan sets), and `%n`. All the others — all the numeric conversions, and the string conversions, _do_ skip leading white space. And the skipped white space includes newlines, of course — so it is very hard to use `scanf()` et al for line-based input. – Jonathan Leffler Nov 12 '17 at 23:04
  • @JonathanLeffler my bad ;) thx I will remember that – Stargateur Nov 12 '17 at 23:08

1 Answers1

2

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

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226