I am trying to open a binary output file to which I need to append some data. I cannot output the data sequentially, so I need to be able to seek within the file stream and cannot use the std::ios::app
flag.
Unfortunately, when opening an output file stream without the std::ios::app
flag, the file gets truncated when it is opened. Here's some 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 every execution to append "Hello World" to the file. However, the file is truncated as soon as it is opened.
What am I doing wrong? If this is a bug in Visual Studio, are there any workarounds?
Edit: Every time the program runs, regardless of whether the file exists or already has contents, the program outputs this:
Offset after opening: 0
Offset at end: 0
Offset after writing: 12
If you open an already existing file for writing, you usually want to overwrite the content of the output file. The open mode std::ios_base::trunc (meaning truncate) has the effect of discarding the file content, in which case the initial file length is set to 0 .
Removes the fractional part of a number and it to an integer. Written by CFI Team. Updated June 12, 2022.
Generally, open the file for reading in text mode, read line after line until the place you want to change, while reading the lines, write them in a second text file you opened for writing. At the place for change, write to the second file the new data. Then continue the read/write of the file to its end.
Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only. Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.
You have to open the file in both output and input mode:
std::fstream file("output.bin", std::ios::in | std::ios::out | std::ios::binary | std::ios::ate);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With