I am trying to write directly to an fstream output buffer to avoid a memcpy
.
Why does the following code not work?
It compiles, runs and produces the right length output file on Linux. But the output file does not contain correct text. Also note that for some reason, when I comment out the two lines involving str2
, then an output file of zero length is produced.
Note: This example does not avoid memcpy
, but if it works, it will help me avoid a memcpy
in my application.
#include <fstream>
int main(int argc, char *argv[]) {
std::fstream out;
char buffer[512];
out.rdbuf()->pubsetbuf(buffer, 512);
out.open("file.txt", std::fstream::out);
char *str1 = "test text.";
strcpy(buffer, str1);
out.rdbuf()->pubseekpos(strlen(str1), std::ios_base::out);
char *str2 = "why?";
out << str2;
out.flush();
out.close();
}