代码之家  ›  专栏  ›  技术社区  ›  Vinayak Deshmukh

C中的低电平I/O

  •  1
  • Vinayak Deshmukh  · 技术社区  · 1 年前

    我正在努力解决K&R C编程书,要求编写一个低级I/O程序,从文件中读取文本并将其打印在屏幕上,如果命令行中没有给出输入文件,则必须从STDIN中获取输入并在屏幕上打印。我认为我已经解决了这个问题,我的代码如下:

    #include <stdio.h>
    #include <fcntl.h>
    #include <unistd.h>
    
    void llfilecopy (int, int);
    
    int main(int argc, char *argv[])
    {
        int ifd, i = 1;
        printf("buffer = %d", BUFSIZ);
    
        if (argc == 1)
            llfilecopy (0, 1);
    
        else
        {
            while (--argc > 0)
            {
                if ((ifd = open(argv[i++], O_RDONLY, 0)) == EOF)
                {
                    printf("cat: cant open %s\n", *argv);
                    return 1;
                }
                else
                {
                    llfilecopy (ifd, 1);
                    printf ("\n\n");
                    close(ifd);
                }
    
            }
        }
        return 0;
    }
    void llfilecopy (int ifd, int ofd)
    {
        char buff [BUFSIZ];
        int n;
    
        while ((n = read (ifd, buff, BUFSIZ)) > 0)
        {
            if (write (1, buff, n) != n)
                printf ("cat: write error on stdout");
        }
    }
    

    然而,我面临着一个我无法解释的有趣问题。 请注意main()后第3行中的printf语句。如果我使用以下内容

    printf("buffer = %d", BUFSIZ);
    

    在屏幕上打印文件后执行此printf。 但是,如果我添加一个“\n”,即e。

    printf("buffer = %d\n", BUFSIZ);
    

    在将文件打印到屏幕之前执行printf。 也许这只是我的一个愚蠢的错误。你能指出这里出了什么问题吗?非常感谢。 我正在使用在线GDB-GCC C编译器 https://www.onlinegdb.com/online_c_compiler#

    1 回复  |  直到 1 年前
        1
  •  3
  •   Lundin    1 年前

    你的目标似乎是行缓冲的,这意味着它在收到“刷新”指令将缓冲区中的所有内容移动到屏幕之前不会更新行。

    冲洗可以通过三种方式进行:

    • 添加 \n 性格到 printf 格式化字符串或等效值(调用 puts 等等)。
    • 明确呼吁 fflush(stdout) .
    • 节目即将结束。