我的机器运行的是 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
重定向到一个文件,它不会刷新换行符。如果您想尝试强制它进行行缓冲,请使用setbuf
或setvbuf
。
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/