我正在尝试读取包含的文件
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)
. - 如果为 true,则执行其主体。
如果您在循环中再次读取该值,您会错过一些东西。
关于c - 逐行读取文件,将整数存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25829578/