kai
kai

Reputation: 1191

Buffering in standard library in C/C++

I have a question about the buffering in standard library for I/O: I read "The Linux Programming Interface" chapter 13 about File I/O buffering, the author mentioned that standard library used I/O buffering for disk file and terminal. My question is that does this I/O buffering also apply to FIFO, pipe, socket and network file?

Upvotes: 1

Views: 417

Answers (2)

Omnifarious
Omnifarious

Reputation: 56038

Yes, if you're using the FILE * based standard I/O library. The only odd thing that might happen is if the underlying system file descriptor returns non-zero for the isatty function. Then stdio might 'line buffer' both input and output. This means it tends to flush when it sees a '\n'.

I believe that it's required to line buffer stdout if file descriptor 1 returns non-zero for isatty.

Upvotes: 1

Adam Rosenfield
Adam Rosenfield

Reputation: 400146

No. Anything that's an ordinary file descriptor (such as those returned by open(2), pipe(2), socket(2), and accept(2)) is not buffered—any data you read or write to it is input or output immediately via direct system calls.

Buffering only happens when you have FILE* objects, which you can get by fopen(3)'ing a regular disk file; the objects stdin, stdout, and stderr are also FILE* objects that are setup at program start. Buffering is usually enabled on FILE* objects, but not always—it can be disabled with setbuf(3), and stderr is unbuffered by default.

If you want to create a buffered stream out of a regular file descriptor, you can do so with fdopen(3).

Upvotes: 0

Related Questions