【问题标题】:How to read all contents of file, including NUL chars between valid text?如何读取文件的所有内容,包括有效文本之间的 NUL 字符?
【发布时间】:2011-03-24 05:34:43
【问题描述】:

我有一个文件需要读入缓冲区 (char *),但问题是该文件在有效文本之间有一些“有趣的字符”。

所以当我编写如下代码时:

  FILE *fp;
  if((fp = fopen(".\\test.txt", "rt"))==NULL){
    printf("Cannot open file2\n");
  }

  fseek(fp, 0, SEEK_END);
  long int fsize = ftell(fp);
  rewind(fp);
  //char *buffer2 = malloc(fsize * sizeof(char));
  buffer = malloc(fsize * sizeof(char));
  fread(buffer, 1, fsize, fp);
  buffer[fsize] = '\0';
  fclose(fp); 

  printf("fsize = %i\n", fsize);
  printf("Buffer = %s\n", buffer);

它只打印出文本文件的第一部分,如下所示:

缓冲区 = 标题

显然停在第一个 NUL 字符处。

他们有什么方法可以读取文件的整个缓冲区,包括有趣的字符吗?

或者这在 C 中是不可能的?

FSIZE被正确读取,只是FREAD没有读取整个缓冲区;-(

任何帮助将不胜感激;-)

谢谢

林顿

更新:好的,我有点愚蠢.....如果我将缓冲区写入一个包含所有内容的文件,只有当我将它写到屏幕上时它才会停在 null 上,所以很好。

【问题讨论】:

    标签: c


    【解决方案1】:

    不要以“文本”模式(“rt”)打开文件,而是使用二进制模式(“rb”)。

    另外,它可能正在读取数据,但printf("Buffer = %s\n", buffer) 只会打印到第一个 NUL,因此您的调试不会按照您的意愿进行。你可能想写一点十六进制转储函数。

    【讨论】:

      【解决方案2】:

      如何读取文件的所有内容,包括有效文本之间的 NUL 字符?

      错误:

      1. 如果尝试创建字符串,请分配足够的空间。 OP的代码短1。如果读取的数据可能包含 空字符,这是一个可疑的目标。

      2. 以二进制模式打开@Lawrence Dol

      3. 更多的错误检查很有用。


      // FILE *fp = fopen(".\\test.txt", "rt");
      FILE *fp = fopen(".\\test.txt", "rb");
      if (fp==NULL) {
        printf("Cannot open file2\n");
        exit(-1);
      }
      
      if (fseek(fp, 0, SEEK_END)) {
        printf("fseek() trouble\n");
        exit(-1);
      }
      long fsize = ftell(fp);
      if (fsize == -1 || fsize >= SIZE_MAX) {
        printf("fell() trouble\n");
        exit(-1);
      }
      // Add 1 if trying to make a string.
      size_t sz = (size_t) fsize;
      if (making_a_string) sz++;
      
      rewind(fp);
      char *buffer = malloc(sizeof *buffer * sz);
      if (buffer == NULL && sz > 0) {  // Tolerate a file size of 0
        printf("malloc() trouble\n");
        exit(-1);
      }          
      
      size_t in = fread(buffer, 1, fsize, fp);
      fclose(fp); 
      if (in != fsize) {
        printf("fread() trouble\n");
        exit(-1);
      }          
      if (making_a_string) {
        buffer[fsize] = '\0';
      }
      

      要打印整个数据,请使用fwrite()。为了打印字符数组,不需要像 string 中那样尾随 null 字符,而是使用字符数组的长度。

       printf("fsize = %ld\n", fsize);  // Note: %ld
       printf("Buffer = <", );
       fwrite(buffer, 1, fsize, stdout);
       printf(">\n");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-02-02
        • 2019-04-25
        • 1970-01-01
        • 1970-01-01
        • 2012-11-06
        • 2011-03-23
        • 1970-01-01
        相关资源
        最近更新 更多