简体   繁体   English

fscanf()在循环中返回相同的模式

[英]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. 以下代码中的fscanf函数一次又一次地在文件中匹配相同的模式,而不是继续前进到下一个模式。 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);
}

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. 检查fscanf的返回值-当它失败时,它不会读取任何内容,因此,如果您循环并再次尝试,将发生相同的情况。 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 这也意味着您不使用feof

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM