Do I need to create my own buffer for file I / O operations in C / C ++?

Do I need to use my own buffer to read or write files in C or C ++ to reduce file I / O?

For example, if you need to read a file record write-by-write (one char at a time or one structure at a time), is it recommended to reduce the number of calls to fread () using a buffer? Does it affect I / O (read and write)? Is the answer responding to the operating system or is there something else not in the code?

I found out it was recommended, but today someone told me about setvbuf()

in stdio.h

and it seems like everything already exists and you don't need to add this complexity to your program.

Looking at stackoverflow I found a non-voting answer , claiming that there is no significant difference between using fgetc

/ setvbuf()

vs. fgets

... It's true?

+3


source to share


3 answers


Functions in <stdio.h>

all do their own buffering. There are exceptions, but generally I expect them to be optimized for the system they are running on, with respect to, for example, buffer size. In which case, I expect use to setvbuf()

be pessimizing in all but a few special cases.



+1


source


The function fread()

already implements buffering to avoid calling the lower level too often read()

. You shouldn't worry about this unless you do some tests and find out that file I / O is taking a long time.



+3


source


The object std::istream

calls the associated object std::streambuf

to actually perform read operations.

The implementation for the istream ( ifstream

) file internally has fstreambuf

one that does exactly that.

0


source







All Articles