且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++如何在ofstream中实际使用pubsetbuf?

更新时间:2023-02-18 15:24:04

按照@pantarei和@lightnes-s-racesinorbit的建议,我将给出答案.如果我违反规定,我深表歉意.

Following the suggestions of @pantarei and @lightnes-s-racesinorbit, I'll write the answer. I apologize if I bent the rules.

根据cppreference站点,设置 pubsetbuf 的顺序很重要,因为需要在打开任何文件之前 进行设置,否则无效.因此,这就是代码的顺序(对于我而言):

According to the cppreference site, the order of setting pubsetbuf matters, because it needs to be set before opening any files, otherwwise it has no effect. So, this is the order of the code as it needs to be (for my case):

int sz {131072};          // buffer size
std::vector<char> buf;   // std::vector instead of C-style char
buf.resize(sz);
std::ofstream outf;      // declaration, only
outf.rdbuf()->pubsetbuf(&buf[0], sz);  // set buffer before...
outf.open("file.txt");                 // ...opening the file
// rest of the code

我的文件通常少于100k,因此***使用128k缓冲区以避免过多的写入.

My files are, most often, below 100k, so a 128k buffer is just fine to avoid too many writes.