【问题标题】:Unexpected value from File read [closed]文件读取中的意外值[关闭]
【发布时间】:2017-03-21 04:57:51
【问题描述】:

我有一个文件 y.txt,其中包含文本 abcdefgh

此代码将文件描述符(int fd)转换为文件指针(FILE*),并尝试从中读取。

#include <stdio.h>
#include<fcntl.h>
int main()
{
    FILE *fp;
    int fd = open("y.txt",O_RDONLY);

    printf("%d",fd);
    fp=fdopen(fd,"r");
    close(fd);
    char a[5];
    a[4]='\0';
    fread(a,2,1,fp);
    printf("%s",a);
    return 0;
}

程序输出p 而不是ab,如果它从y.txt 的开头读取它应该输出。

我做错了什么?

【问题讨论】:

  • 请先阅读How to Ask页面。
  • 好吧,我知道它不好,我真的很抱歉,但请告诉我为什么当我将 fd 转换为文件指针时为什么它没有给我正确的答案。它给了我 p 但是y.txt 包含:abcdefg
  • 也许可以试试fopen 而不是open/fdopen
  • yano: fopen 不使用文件描述符打开文件。我只是将文件描述符转换为文件指针
  • a) 在读取文件之前不要关闭文件,b) 在每个 printf 语句的末尾添加 \n,c) 读取 4 字符来填充字符串,用fread(a,4,1,fp);

标签: c operating-system


【解决方案1】:

我发现您的代码有问题。在完成 fp 之前,您 close(fd),这可能导致您对 fread 的调用失败。这是因为当你使用fdopen:

文件描述符没有被复制。

意味着当您运行close(fd) 时,fp 试图从中读取的底层文件将被关闭。要解决此问题,您可以删除对close 的调用并添加对fclose 的调用,这也应该关闭fd

如果你真的只想要一个FILE *,你应该可以使用fopen 打开它,同时跳过fd

【讨论】:

    【解决方案2】:

    考虑你的代码:

    char a[5];
    a[4]='\0';
    fread(a,2,1,fp);
    

    这会给你一个 5 个字符的字符串。它是一个“自动”变量,未初始化。然后用'\0' 终止字符串。好的。然后你 fread 一个大小为 2 的项目。所以字节 3 和 4 仍然是垃圾。这有帮助吗?

    【讨论】:

      【解决方案3】:

      以下是对程序的一些更正,如代码中所述。

      #include <stdio.h>
      #include <io.h>                         // added header
      #include <fcntl.h>
      
      int main()
      {
          FILE *fp;
          int fd = open("y.txt",O_RDONLY);
      
          printf("%d\n",fd);                  // add a newline for clarity
          fp=fdopen(fd,"r");
          //close(fd);                        // do not close before reading!
          char a[5];
          a[4]='\0';
          fread(a,4,1,fp);                    // read 4 chars to fill the string space
          printf("%s\n",a);                   // add a newline for clarity
          close(fd);                          // close after reading
      
          return 0;
      }
      

      文件输入:

      abcde
      

      程序输出:

      3
      abcd
      

      虽然一开始最好有更简单的

      FILE *fp = fopen("y.txt", "r");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-11
        • 2012-03-06
        • 1970-01-01
        • 2018-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多