fputs and fflush, writing and buffer process

独自空忆成欢 提交于 2020-01-23 13:26:22

问题


I'm confused as to how the writing processing goes in C. So I have a string, s, that I want to write to the output. To do that, I use fputs:

fputs(s, stdout);

But apparently this does not write to the output, but merely collect the data for writing? Where exactly is it collected? So I have to wait until the program exits or till I call fflush() till the output is actually written into stdout? Am I right?


回答1:


The C Standard IO streams are operating in one of three modes:

  1. fully buffered
  2. line buffered
  3. unbuffered

You can set the mode with the setvbuf() function. This all happens deep in the guts of the Standard IO implementation. If you want your data to appear immediately, use unbuffered mode.

Quoting from 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 thesetbufandsetvbuf functions.



来源:https://stackoverflow.com/questions/22076566/fputs-and-fflush-writing-and-buffer-process

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!