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

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

但是我得到的输出全是 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;

}

它的工作原理如下:

  1. 检查(fscanf(fatfile, "%d", &number) == 1) && (i < 32) .
  2. 如果为 true,则执行其主体。

如果您在循环中再次读取该值,您会错过一些东西。

关于c - 逐行读取文件,将整数存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25829578/

相关文章:

c - 如何在C中生成唯一的ID

objective-c - 当 int 在另一个循环中递增时如何管理它?

java - 创建 int 数组的字符串数组时出现问题

c - 如何对LLVM位码文件进行整个程序优化

c - 如何使用直接来自函数的返回值作为位串而不是格式化数字?

C 从字符串的一部分获取数值

java - 一起使用 String 和 int 时的 System.out.println 行为

c - 如何从函数中使用 malloc?

c - 类型转换 : double to char: multiple questions

c - 中断处理程序是否像这样运行,运行多长时间?