a concerned citizen a concerned citizen - 1 year ago 128
C++ Question

C++ How to actually use pubsetbuf in ofstream?

I have a program that writes a temporary file to be used with gnuplot. The file varies in size and it can get to several hundreds of kB, if not MB. Everytime it's written to disk,

only shows some 8kB at a time. I would like to avoid unnecessary disk writes by setting a buffer greater than this. One of the answers here, on SO, said that 128kB is about the maximum before it starts behaving badly. I have searched and found out that I can modify the buffer, something like this:

int sz {65536};
char buf[sz];
std::ofstream outf {"file.txt"};
outf.rdbuf()->pubsetbuf(&buf[0], sz);

So far, so good, it compiles, but how do I actually use this buffer? In one of the answers, I've seen using
, but it I don't really understand what's going on there. The C++ reference site isn't very helpful, either. I am not an advanced programmer, can someone please show me how to use this? I am using
, and the file written has both data for plotting, and various settings based on conditionals, so I don't know how to fit those in the buffer.

Answer Source

The reference documentation clearly states (emphasis mine):

2) The base class version of this function has no effect. The derived classes may override this function to allow removal or replacement of the controlled character sequence (the buffer) with a user-provided array, or for any other implementation-specific purpose.

So what you'll need to extend the buffer is std::basic_filebuf::setbuf() instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download