简体   繁体   中英

Does fwrite buffer the output?

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?

ie 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.

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 .

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.

FILE* I/O can be buffered but it does not have to be (it can be different for each stream). Furthermore, there are multiple ways to do buffering (fully buffered where the buffer is not flushed until it is full or an explicit call to fflush is made or line buffered where the buffer is not flushed until it sees an EOL). It is also possible to turn off buffering altogether.

You can change the type of buffering with the setvbuf call.

It depends on the library implementation. You might take a look at something like dtruss or strace to see what system calls are actually invoked by the implementation.

Why do you care about this?

I don't believe the standards says anything about this but in general: no the operating system will decide how many I/O operations to do. It could be 1 it could be 10. It could even be more if the data size is large. Most operating systems allow you to control how I/o should behave but AFAIK there's no portable way to do it. (and often you don't want to anyway)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM