打开没有截断的二进制输出文件流 [英] Opening a binary output file stream without truncation

查看:101
本文介绍了打开没有截断的二进制输出文件流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图打开一个二进制输出文件,我需要附加一些数据。我不能顺序地输出数据,所以我需要能够在文件流中搜索,不能使用 std :: ios :: app 标志。

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. 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;
}



我希望每次执行都将Hello World附加到文件。但是,该文件在打开时会被截断。

I would expect every execution to append "Hello World" to the file. However, the file is truncated as soon as it is opened.

我做错了什么?如果这是Visual Studio中的错误,是否有任何解决方法?

What am I doing wrong? If this is a bug in Visual Studio, are there any workarounds?

编辑:
每次程序运行时,无论文件是否存在内容,程序输出:

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

这篇关于打开没有截断的二进制输出文件流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆