Yes, all stream operations are buffered, though by default the standard input, output and error output are not so that interactions with the C IO is less surprising.
As already alluded, there is a base class streambuf that is used behind the scenes. It is provided with its own buffer, which size is an implementation detail.
You can check (experimentally) how much this buffer is by using streambuf::in_avail, assuming that input filestream and output filestream are setup with the same buffer size…
There are two other operations that you can do here that might be of interest:
- you can change the
streambufobject used by a stream, to switch to a custom version - you can change the buffer used by the
streambufobject
both should be done either right after creating the stream or after a flush, lest some data is lost…
To illustrate the buffer change, check out streambuf::putsetbuf:
#include <fstream>
#include <vector>
int main () {
std::vector<char> vec(512);
std::fstream fs;
fs.rdbuf()->pubsetbuf(&vec.front(), vec.size());
// operations with file stream here.
fs << "Hello, World!\n";
// the stream is automatically closed when the scope ends, so fs.close() is optional
// the stream is automatically flushed when it is closed, so fs.flush() is optional
return 0;
}
Now you can repeat the experiments you did in C to find the sweet spot 🙂