以下代码中的 fscanf 函数在文件中一遍又一遍地匹配相同的模式,而不是继续处理下一个模式。我该如何解决这个问题?
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);
}
最佳答案
检查 fscanf 的返回值——当它失败时,它不会读取任何内容,所以如果你循环并重试,同样的事情会发生。相反,你需要类似的东西:
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 );
}
}
这也意味着您 don't use feof
关于c - fscanf() 在循环中返回相同的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47253135/