以下代码中的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);
}
答案 0 :(得分:2)
检查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