【问题标题】:Reading the contents of a file into a buffer in C将文件的内容读入C中的缓冲区
【发布时间】:2021-09-26 15:37:43
【问题描述】:

我正在开发一个程序,该程序读取 csv 文件中的每个整数并将其复制到缓冲区中,以便以后可以使用它来构建二叉搜索树。我会展示我的代码,然后我会解释我遇到的问题:

代码-

int *createBuffer(int count) {
  FILE *file = fopen(FILE1, "r");
  int buffer[count + 1];
  int *bufferPointer = buffer;
  int number;
  int ch;
  int i = 0;
  while (1) {
      ch = fgetc(file);
      if(ch == EOF){
          break;
      }
    if (fscanf(file, "%i", &number)) {
      buffer[i] = number;
      i++;
    } 
  }
  return bufferPointer;
}

Count 是指文件中存在的逗号数,因此我可以为数组中的每个数字分配足够的空间。文件指针指向我以只读模式打开的文件。缓冲区是使用上述计数变量创建的。 bufferPointer 是指向我从函数返回的缓冲区的指针。 while 循环一直运行到变量 ch 等于 EOF 时才会中断。 if 语句的目的基本上是扫描文件中的整数并将它们读入 number,然后将 number 复制到下一个缓冲区索引中。最后返回缓冲区指针。

这段代码给了我非常奇怪的结果。当我打印缓冲区时,我得到了结果:

9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 850045856 0 -2141008008 32767 0 0 214814639 1 0 0 -2141007448 32767 0 0 214814639 1 -487430544 32766 539243238 32767 -2141007448 32767 6 0 -487430496 32766 539279361 32767 0 0 0 0 0 0 0 0 -487430272 32766 539271526 32767 92 68 68 0 0 0 69 0 -2141007976 32767 0 0 42 68 55 46 10 40 44 100 75 63 19 13 10 95 43 47 47 49 59 40 0 0 -2141006600 % 

这很奇怪,因为虽然我得到了一些垃圾值,但从 42...40 的整个序列与我的数据文件中的数字匹配。我不确定这段代码哪里出错了,所以如果有人知道,请分享。

与往常一样,如果您花时间回答或尝试回答此问题,感谢您抽出宝贵时间。如果您需要进一步说明,请随时询问。

【问题讨论】:

  • 非常感谢您的有用评论。这(很大程度上)解决了我的问题。我仍然需要解决一些问题,但现在 90-95% 的原始值都在缓冲区中,并且我没有垃圾值。我会将此标记为答案,但我认为我不能为 cmets 做到这一点。
  • if (fscanf(file, "%i", &number)) 毫无意义。 if (fscanf(file, "%i", &number)==1) 有点道理。
  • 我相信,无论哪种方式,它都会返回一个真实的值,但是是的,您的建议使代码更具可读性。谢谢!
  • @AnishSinha,如果fscanf 返回 EOF 而不是零怎么办?我认为我从未见过 Chux 推荐一些没有意义的东西。明确检查来自scanf 的返回值不仅仅是编码风格建议。
  • @AnishSinha 确实,代码在 EOF 上中断,但为时已晚。 buffer[i] = number; i++; 可能由于 fscanf(file, "%i", &number) 返回 EOF 而发生。现在下面的代码不知道buffer[]最后一项是否是垃圾。

标签: arrays c file file-processing


【解决方案1】:

This 是您的代码的“固定”版本。但是您会注意到它不打印第一个字符。假设,如果文件中的第一个数字是 220,那么它将打印 20。
原因是-您的程序首先从c=fgetc(file) 中的文件中删除一个字符。所以在第一次迭代时,它会删除第一个字符2 from 220,然后将 20 存储在内存中。认为在其余迭代中不会出现此问题,因为在这些情况下第一个字符是逗号。
为了解决这个问题,我们可以将c=getc(file) 放在循环的末尾。这样,进入循环后,读取第一个数字,去掉逗号,读取下一个数字,去掉逗号......

#include<stdio.h>
#include<stdlib.h>

int *createBuffer(int count) {
  FILE *file = fopen("filename.txt", "r");
  int* buffer = (int*)malloc(sizeof(int)*(count + 1));
  int number;
  int ch;
  int i = 0;
  while (1) {
      if (fscanf(file, "%i", &number)) {
      buffer[i] = number;
      i++;
    } 
    ch = fgetc(file);
      if(ch == EOF){
      break;
    }
  }
  
  return buffer;
}

void main(){
  int* arr = createBuffer(10);
  for(int i=0; i<10; i++){
    printf("%d ",arr[i]);
  }
  printf("\n");
}

【讨论】:

    猜你喜欢
    • 2015-08-20
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 2013-05-20
    • 2012-12-09
    • 1970-01-01
    • 2018-07-21
    • 2019-07-01
    相关资源
    最近更新 更多