难道printf的总是冲在遇到一个新行的缓冲区? [英] Does printf always flush the buffer on encountering a newline?
问题描述
我的机器运行Ubuntu 10.10,和我使用标准的GNU C库。我认为,如果有格式字符串描述一个换行符。printf刷新缓冲区中的IM pression下,但是下面的code反复似乎逆势这一趋势。有人能解释,为什么缓冲区不会被刷新。
的#include<&stdio.h中GT;
#包括LT&;&unistd.h中GT;
#包括LT&;&fcntl.h GT;
#包括LT&; SYS / wait.h>诠释的main()
{
INT RC;
关闭(1);
接近(2);
的printf(HI 1 \\ n);
fprintf中(标准错误,错误。\\ n); 开放(newfile.txt,O_WRONLY | O_CREAT | O_TRUNC,0600);
的printf(什么\\ n吗?);
fprintf中(标准错误,我说错误。\\ n); RC =叉(); 如果(RC == 0)
{
的printf(再说\\ n吗?);
fprintf中(标准错误,ERROR错误。\\ n);
}
其他
{
等待(NULL);
} 的printf(BYE \\ n);
fprintf中(标准错误,HI 2 \\ n); 返回0;
}
newfile.txt的运行该程序后的内容如下:
HI 1
什么?
再说一遍?
BYE
HI 1
什么?
BYE
没有,标准说,标准输出
最初完全缓冲如果输出设备可以被确定为非交互式的。
这意味着,如果您重定向标准输出
到一个文件,它不会换行冲洗。如果你想尝试和力的它行缓冲,使用则setbuf
或 setvbuf用来
C99的相关部分, 7.19.3文件,第7段
,规定:
目前程序启动时,三个文本流是predefined并且不需要明确地打开 - 标准输入(用于读取传统的输入),标准输出(写入常规输出),以及标准误差(用于写入诊断输出)。由于刚打开,标准错误流不会完全缓冲;标准输入和标准输出流是完全缓冲当且仅当可确定该流不提及交互设备
块引用>只要记住节
5.1.2.3/6
:
什么构成一个互动装置是实现定义的。
块引用>My machine is running ubuntu 10.10, and I'm using the standard gnu C library. I was under the impression that printf flushed the buffer if there was a newline described in the format string, however the following code repeatedly seemed to buck that trend. Could someone clarify why the buffer is not being flushed.
#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; }
The contents of newfile.txt after running this program is as follows.
HI 1 WHAT? SAY AGAIN? BYE HI 1 WHAT? BYE
解决方案No, the standard says that
stdout
is initially fully buffered if the output device can be determined to be a non-interactive one.It means that, if you redirect
stdout
to a file, it won't flush on newline. If you want to try and force it to line-buffered, usesetbuf
orsetvbuf
.The relevant part of C99,
7.19.3 Files, paragraph 7
, states: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.
Just keep in mind section
5.1.2.3/6
:What constitutes an interactive device is implementation-defined.
这篇关于难道printf的总是冲在遇到一个新行的缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!