【问题标题】:Write through a pipe with fputc使用 fputc 通过管道写入
【发布时间】:2013-11-10 23:21:39
【问题描述】:

由于某种原因,当我尝试使用 fputc 通过管道写入时,我的程序无法运行;但是,当我使用 write 系统调用时,它工作正常。这是我使用 fputc 的部分代码:

    FILE *input = fopen(argv[1], "rb");
    FILE *toSort = fdopen(ps_fd[1], "wb");
    /* close the side of pipe I am not going to use */
    close (ps_fd[0]);
    char temp;
    char buf[1];
    while ((temp=fgetc(input)) != EOF)
    {
        buf[0] = (char)temp;
        fputs(buf, toSort);
        buf[0] = '\0';
    }
    fputs(buf, toSort);
    close(ps_fd[1]);

【问题讨论】:

    标签: c redirect fork pipe


    【解决方案1】:

    fputs()之后使用fflush(toSort)

    【讨论】:

      【解决方案2】:

      问题标题询问fputc(),但代码(错误)使用fputs()

      请注意,fputs() 需要一个以 null 结尾的字符串。它不适用于二进制数据;它不会写入零(或空)字节。

      另外,你不是空终止字符串。您没有为空终止提供足够的存储空间。您没有正确关闭文件。您应该使用int temp,因为fgetc() 返回的是int,而不是char。使用fputs() 所需的最小更改是:

      FILE *input = fopen(argv[1], "rb");
      FILE *toSort = fdopen(ps_fd[1], "wb");
      close(ps_fd[0]);
      int temp;
      char buf[2] = ""; // Two characters allocated; null terminated
      while ((temp = fgetc(input)) != EOF)
      {
          buf[0] = (char)temp;
          fputs(buf, toSort);
      }
      fclose(toSort);  // fclose() to flush the buffered data
      

      或者,使用fputc()

      FILE *input = fopen(argv[1], "rb");
      FILE *toSort = fdopen(ps_fd[1], "wb");
      close(ps_fd[0]);
      int temp;
      while ((temp = fgetc(input)) != EOF)
          fputc(temp, toSort);
      fclose(toSort);
      

      【讨论】:

        猜你喜欢
        • 2011-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-25
        相关资源
        最近更新 更多