Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does fwrite buffer the output?

Tags:

c++

In C++, there is an std::fwrite() which writes a buffer to a file on disk.

Can you please tell me if there is any buffer inside that fwrite implementation?

i.e. if I call fwrite() multiple times (say 10 times), does it actually invoke file I/O 10 different times?

I am asking this for Ubuntu 10.04 environment.

like image 370
michael Avatar asked May 10 '10 20:05

michael


People also ask

Is fread buffered?

fread() is part of the C library, and provides buffered reads. It is usually implemented by calling read() in order to fill its buffer.

How does fwrite work in C?

The fwrite() function writes the data specified by the void pointer ptr to the file. ptr : it points to the block of memory which contains the data items to be written. size : It specifies the number of bytes of each item to be written. n : It is the number of items to be written.

Is fwrite safe?

fwrite() is a function that writes to a FILE*, which is a (possibly) buffered stdio stream. The ISO C standard specifies it. Furthermore, fwrite() is thread-safe to a degree on POSIX platforms.

What is buffering in file handling?

Buffering is the process of storing a chunk of a file in a temporary memory until the file loads completely.


2 Answers

Yes, it is buffered. The size of the buffer is defined by BUFSIZ. (Thanks @ladenedge.) Ten sufficiently large operations will result in ten system calls.

You are also allowed to set your own buffer using std::setbuf and std::setvbuf.

The functions in cstdio are inherited from C. The preferred interface in C++ is fstream and filebuf.

like image 118
Potatoswatter Avatar answered Sep 29 '22 10:09

Potatoswatter


It depends. On most platforms, file IO is cached hence the fflush() call exists to write cached data to disk - in that respect, the answer to your first question is (usually) "yes", and your second "no". That said, it's not guaranteed to be that way by any stretch of the imagination for any particular platform - generally, the standards only specify the interface for such functions, not their implementation. Also, its quite possible that calling fwrite() will cause an implicit flush if the cache becomes "full", in which case calling fwrite() may in fact trigger file IO - especially if calling fwrite() with large amounts of data.

like image 24
Mac Avatar answered Sep 29 '22 11:09

Mac