Why fprintf doesn't write directly into the file unless fflush() is used?

半腔热情 提交于 2019-11-28 11:40:32

问题


I have written a daemon that writes a value in a file. What I have observed is that when I keep writing on a file, there is nothing visible in the file. in other hand, If I use fflush() method then the characters are visible in the file. Why fflush() makes a difference?


回答1:


Because it's buffered. That means all writes are stored in a buffer in memory until the buffer is flushed. For printf and friends it's when it has either a newline, or you explicitly call fflush, or of course if the buffer becomes full.




回答2:


By default, stdio is fully buffered, unless it's writing to a terminal, in which case it's line-buffered, or stderr, which is not buffered at all.

You can disable buffering with the setbuf() function.

setbuf(fp, NULL);



回答3:


fprintf is an IO routine provided by the libc, it use caching mechanism by default, before doing a real write into files.

Characters are normally accumulated and transmitted asynchronously to the file in a block, so the cache must exceed the libc(stdio) internal buffer size (BUFSIZE, #defined in stdio.h) or when a fflush() has occurred.

If you want to minimize the caching i suggest you to use O_DIRECT or O_SYNC flags for your open call, but there is some restrictions: you must ensure alignment of your buffers and other stuffs. Read the O_DIRECT section of man 2 open .

you may also read this for further informations on how to control libc buffering.



来源:https://stackoverflow.com/questions/20267244/why-fprintf-doesnt-write-directly-into-the-file-unless-fflush-is-used

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