繁体   English   中英

将文件内容读入C中的缓冲区

[英]Reading the contents of a file into a buffer in C

我正在开发一个程序,该程序读取 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;
}

计数是指文件中存在的逗号数,因此我可以为数组中的每个数字分配足够的空间。 文件指针指向我以只读模式打开的文件。 缓冲区是使用上述计数变量创建的。 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 的整个序列与我的数据文件中的数字相匹配。 我不确定我在这段代码中哪里出错了,所以如果有人知道,请分享。

与往常一样,如果您花时间回答或尝试回答这个问题,感谢您的时间。 如果您需要进一步说明,请随时提出。

是您的代码的“固定”版本。 但是您会注意到它不打印第一个字符。 假设您的文件中的第一个数字是 220,那么它将打印 20。
原因是 - 您的程序首先从c=fgetc(file)文件中取出一个字符。 所以在第一次迭代时,它2 from 220取出第一个字符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");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM