我对 C 中的写入处理方式感到困惑。所以我有一个字符串 s,我想将其写入输出。为此,我使用 fputs:
fputs(s, stdout);
但显然这不会写入输出,而只是收集写入数据?具体是在哪里采集的?所以我必须等到程序退出或直到我调用 fflush() 直到输出实际写入标准输出?我说得对吗?
最佳答案
C 标准 IO 流以三种模式之一运行:
- 完全缓冲
- 行缓冲
- 无缓冲
您可以使用 setvbuf() 设置模式功能。这一切都发生在标准 IO 实现的深处。如果您希望您的数据立即出现,请使用无缓冲模式。
引用自 C99 7.19.3#3:
When a stream is unbuffered, characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters may be accumulated and transmitted to or from the host environment as a block. When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled. When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered. Furthermore, characters are intended to be transmitted as a block to the host environment when a buffer is filled, when input is requested on an unbuffered stream, or when input is requested on a line buffered stream that requires the transmission of characters from the host environment. Support for these characteristics is implementation-defined, and may be affected via the
setbuf
andsetvbuf
functions.
关于c - fputs和fflush,写入和缓冲过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22076566/