c - printf 是否总是在遇到换行符时刷新缓冲区?

标签 c posix

我的机器运行的是 ubuntu 10.10,我使用的是标准 gnu C 库。我的印象是,如果格式字符串中描述了一个换行符,printf 会刷新缓冲区,但是下面的代码似乎反复出现了这种趋势。有人可以澄清为什么缓冲区没有被刷新。

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>

int main()
{
    int rc;
    close(1);
    close(2);
    printf("HI 1\n");
    fprintf(stderr, "ERROR\n");

    open("newfile.txt", O_WRONLY | O_CREAT | O_TRUNC, 0600);
    printf("WHAT?\n");
    fprintf(stderr, "I SAID ERROR\n");

    rc = fork();

    if (rc == 0)
    {
        printf("SAY AGAIN?\n");
        fprintf(stderr, "ERROR ERROR\n");
    }
    else
    {
        wait(NULL);
    }

    printf("BYE\n");
    fprintf(stderr, "HI 2\n");

    return 0;
}

运行该程序后newfile.txt的内容如下。

HI 1
WHAT?
SAY AGAIN?
BYE
HI 1
WHAT?
BYE

最佳答案

不,标准说如果输出设备可以确定为非交互式设备,则 stdout 最初是完全缓冲的。

这意味着,如果您将 stdout 重定向到一个文件,它不会刷新换行符。如果您想尝试强制它进行行缓冲,请使用setbufsetvbuf

C99 的相关部分,7.19.3 文件,第 7 段,指出:

At program startup, three text streams are predefined and need not be opened explicitly - standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.

请记住 5.1.2.3/6 部分:

What constitutes an interactive device is implementation-defined.

关于c - printf 是否总是在遇到换行符时刷新缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5229096/

相关文章:

iphone - 在 mac 中制作 arm 架构 c 库

c - POSIX 线程/信号 : Portable way to determine to which thread a signal was delivered?

c - 为什么在使用 scanf 输入值时在 %d 和 %c 之间放置空格

C:二维数组是如何工作的?

从 Java 应用程序问题调用新的 PostgreSQL 命令

c++ - C++中的POSIX线程编程

c - 获取socket读操作的进度

perl - 为什么我不从我的子进程中获取退出状态?

c++ - 客户端断开连接时 TCP 套接字选择服务器段错误

c - 在位数组中使用什么数据类型