It is partly performance and partly control over how stream library functions (fread, fgets, fprintf, etc.) relate to actual I/O to a device/file.
For example, stream output to a character device (e. g. your terminal) are, by default, line buffered. The effect of this is that the following code,
printf("start ");
sleep(10);
printf("stop
");
will wait 10 seconds and then print start stop
[NL]. The first print was buffered because there was no new-line to flush the buffer. To get start
to print, then sleep 10 seconds,you could either add a fflush
call before the sleep
call, or turn off buffering on stdout
with setvbuf
.
Stream output to a block device or disk file is, by default, fully buffered. This means that the buffer won't flush until either you overflow the buffer or do an fflush
. This could be a problem with files, for example, if you want to monitor the output in real-time with tail -f
. If you know that this monitoring may be done, you could switch the stream to line-buffering so that every time a new-line is printed, the buffer is flushed to the file. This would be at the cost of increased overhead as disk blocks are written several times as new-lines are printed. (Note: this overhead depends on how the file system is mounted. A fixed drive, mounted write-back cache, will have less overhead as the OS buffers writes to the disk, vs. a removable drive mounted write-though. In the latter case, the OS will try to do the partial writes to improve the chances of avoiding data loss if the drive is removed without dismounting.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…