逐行读取文件,在数组中存储整数

时间:2014-09-14 02:35:14

标签: c int

我试图读取包含

的文件

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);

然而输出im得到全是0

我该如何正确地做到这一点

1 个答案:

答案 0 :(得分:1)

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;

}

它的工作原理如下:

  1. 检查(fscanf(fatfile, "%d", &number) == 1) && (i < 32)
  2. 如果是,则执行其正文。
  3. 如果你在循环中再次读取该值,你会错过一些东西。

相关问题