我正在尝试读取包含以下内容的文件
000101001001010000000000000(每个数字在新行中)
这是即时通讯使用的代码
FILE *fatfile;
int i;
i = 0;
fatfile = fopen("fat.dat", "r");
if(fatfile == NULL)
{
perror("Error while opening file");
}
int number;
while((fscanf(fatfile, "%d", &number) == 1) && (i < 32))
{
fscanf(fatfile, "%d", &number);
fat[i] = number;
i++;
}
fclose(fatfile);
但是我得到的输出都是0
我如何正确地做到这一点
最佳答案
while((fscanf(fatfile, "%d", &number) == 1) && (i < 32))
{
// you already read the number from the file above,
// you need to save it after read the new value.
// and fscanf is executed every time since it's in the while's condition.
fat[i++] = number;
}
它是这样的:
检查
(fscanf(fatfile, "%d", &number) == 1) && (i < 32)
。如果为真,则执行其主体。
如果您在循环中再次读取该值,则会丢失某些内容。