简体   繁体   中英

Opening a binary output file stream without truncation

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

您必须在输出输入模式下打开文件:

std::fstream file("output.bin", std::ios::in | std::ios::out | std::ios::binary | std::ios::ate);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM