有人可以解释一下 stdio 缓冲是如何工作的吗?

标签 c buffer stdio

我不明白缓冲区是干什么的,怎么用的。 (另外,如果你能解释缓冲区通常做什么) 特别是,为什么在此示例中需要 fflush?

int main(int argc, char **argv)
{
    int pid, status;
    int newfd;  /* new file descriptor */

    if (argc != 2) {
        fprintf(stderr, "usage: %s output_file\n", argv[0]);
        exit(1);
    }
    if ((newfd = open(argv[1], O_CREAT|O_TRUNC|O_WRONLY, 0644)) < 0) {
        perror(argv[1]);    /* open failed */
        exit(1);
    }
    printf("This goes to the standard output.\n");
    printf("Now the standard output will go to \"%s\".\n", argv[1]);
    fflush(stdout);

    /* this new file will become the standard output */
    /* standard output is file descriptor 1, so we use dup2 to */
    /* to copy the new file descriptor onto file descriptor 1 */
    /* dup2 will close the current standard output */

    dup2(newfd, 1); 

    printf("This goes to the standard output too.\n");
    exit(0);
}

最佳答案

在 UNIX 系统中,stdout 缓冲恰好可以提高 I/O 性能。 每次都做 I/O 会非常昂贵。

如果你真的不想缓冲,有一些选择:

  1. 禁用缓冲调用setvbuf http://www.cplusplus.com/reference/cstdio/setvbuf/

  2. 当你想刷新缓冲区时调用flush

  3. 输出到 stderr(默认无缓冲)

这里有更多详细信息:http://www.turnkeylinux.org/blog/unix-buffering

I/O 是一个昂贵的操作,所以为了减少 I/O 操作的次数,系统将信息存储在一个临时的内存位置,并延迟 I/O 操作到有大量数据的时刻.

这样您的 I/O 操作数量就会少得多,这意味着应用程序会更快。

关于有人可以解释一下 stdio 缓冲是如何工作的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29176636/

相关文章:

c - 初始化结构中的零数组会导致错误

Java 套接字异常 : No buffer space available

Golang - 如何克服 bufio 的 Scan() 缓冲区限制?

c - 谁免费的 setvbuf 缓冲区?

C 编程。尝试循环诱使用户输入正数

c - MCP3021字节处理

c - 堆内存中的一个奇怪问题!

c - 我的解释正确吗?我可以打印 double 的二进制表示形式,例如 :1?

c - 缓冲区未正确读取字符串

c - 将 fgets 与 scanf 混合使用并使用 fseek 跳过换行符是否是一种不好的做法? C