I am trying to open a binary output file to which I need to add some data. I cannot output data sequentially, so I need to search the file stream and not use the std::ios::app flag.
Unfortunately, when opening a stream of output files without the std::ios::app flag, the file becomes truncated when it is opened. Here is a sample code:
#include <iostream> #include <fstream> int main() { std::ofstream file("output.bin", std::ios::binary | std::ios::ate); std::streamoff orig_offset = file.tellp(); std::cout << "Offset after opening: " << orig_offset << std::endl; file.seekp(0, std::ios::end); std::streamoff end_offset = file.tellp(); std::cout << "Offset at end: " << end_offset << std::endl; file << "Hello World" << std::endl; std::streamoff final_offset = file.tellp(); std::cout << "Offset after writing: " << final_offset << std::endl; return 0; }
I would expect each execution to add "Hello World" to the file. However, the file is truncated as soon as it opens.
What am I doing wrong? If this is a bug in Visual Studio, are there any workarounds?
Edit: Each time the program starts, regardless of whether the file exists or not, the program displays this:
Offset after opening: 0 Offset at end: 0 Offset after writing: 12
source share