简体   繁体   English

打开二进制输出文件流而不截断

[英]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. 我不能按顺序输出数据,所以我需要能够在文件流中搜索并且不能使用std::ios::app标志。

Unfortunately, when opening an output file stream without the std::ios::app flag, the file gets truncated when it is opened. 不幸的是,在没有std::ios::app标志的情况下打开输出文件流时,文件在打开时会被截断。 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. 我希望每次执行都将“Hello World”附加到文件中。 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? 如果这是Visual Studio中的错误,是否有任何变通方法?

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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