【问题标题】:writing and reading an array of integers from a binary file从二进制文件中写入和读取整数数组
【发布时间】:2023-03-04 20:54:01
【问题描述】:

您好,我正在尝试从文件中写入和读取整数数组,但是,我用来读取它们的循环处于无限循环中。我将如何修复这个无限循环,以便当它到达文件末尾时退出循环。另外,我不完全确定 fread 是否在做我期望的事情。

 FILE *fptr = fopen("number.db", "wb");
 int nums[100] = {1,2,3,4,5,6,7,8,9,100,101,102,103,104,105};
 int nums2[100];

 fwrite(nums,sizeof(int),15,fptr);
 fclose(fptr);

 fptr = fopen("number.db", "rb");
  fseek(fptr,0,SEEK_END);
  long end = ftell(fptr); //finds length of the file
  fseek(fptr,0,SEEK_SET);

 while(!feof(fptr)){
   int counter = 0;
   fread(nums2,sizeof(int),1,fptr);
   fseek(fptr,counter,SEEK_SET);
   counter++;
   if(counter>=end){ //Breaks when it seeks to the end
      break;
    }
 fclose(fptr);

我觉得 fread 的逻辑有些问题,但我不太确定。当我打印出保存在“nums2”中的数字时,它只是读取的最后一个数字:nums2 的所有元素都是 105。

【问题讨论】:

  • 这是一个无限循环,因为您在循环中每次都将 counter 初始化为 0,而 fseek 将指针指向文件的开头。在循环之外取出int counter = 0;
  • fread(nums2,sizeof(int),1,fptr); --> fread(nums2+counter, sizeof(int),1,fptr); , 需要end /= sizeof(int);

标签: c file loops while-loop binary


【解决方案1】:

问题在于搜索/计数器初始化的组合。

如果您每次都将计数器设置为 0(第一条记录)并且您寻找它,那么您将始终处于文件记录中的“有效范围”内。文件结束条件永远不会发生,因此,while 查找将进入无限循环

我确实相信 if 条件 "if(counter>=end)" 也是无用的,我会删除它。 while 循环将在 eof 一次完成,这是它应该的方式。

 FILE *fptr = fopen("number.db", "wb");
 int nums[100] = {1,2,3,4,5,6,7,8,9,100,101,102,103,104,105};
 int nums2[100];

 fwrite(nums,sizeof(int),15,fptr);
 fclose(fptr);

 fptr = fopen("number.db", "rb");
 fseek(fptr,0,SEEK_END);
 long end = ftell(fptr); //finds length of the file
 fseek(fptr,0,SEEK_SET);
 int counter = 0;
 while(!feof(fptr)){
      fread(nums2,sizeof(int),1,fptr);
      fseek(fptr,counter,SEEK_SET);
      counter++;
      if(counter>=end){ //Breaks when it seeks to the end
           break;
      }
 }
 fclose(fptr);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 2014-09-25
    相关资源
    最近更新 更多