c++ - 在 C++ 中写入现有的空格二进制文件

标签 c++

我正在尝试通过 C++ 在特定位置写入大小为 1 MB 的现有空白二进制文件。

ofstream of( filename, ofstream::binary );
of.seekp(1600, of.beg);
of.write(arr, 1024);
of.close();

空白文件是通过将此缓冲区写入文件之前创建的:

char *buffer = (char*)malloc(size);     
memset(buffer, ' ', size);

但是这段代码只是截断了整个1MB的空白文件并写入了这1KB的内容,文件的大小变成了1KB。

也尝试使用 app 以及 ate 模式。当我像这样尝试 app 模式时:

ofstream of( filename, ofstream::binary | ofstream::app );
of.seekp(1600, of.beg);
of.write(arr, 1024);
of.close();

它将内容添加到文件末尾。因此文件大小为 1MB+1KB。

我想做的是用一些数据覆盖文件中的 1KB 数据(目前它是空白空间)。这样它就不会更改文件大小或任何其他数据。

我哪里做错了?

最佳答案

使用

ofstream of( filename, ofstream::binary | ofstream::in | ofstream::out)

打开二进制文件进行更新。

参见 C++11 表 123 - 文件打开模式(在 27.9.1.4/3 中):

Table 132 — File open modes

 ios_base flag combination          stdio 
binary  in   out  trunc  app       equivalent
---------------------------------------------------
              +                      "w"    truncate/create for writing
              +           +          "a"    append - writes automatically seek to EOF
                          +          "a"    
              +     +                "w"    
        +                            "r"    open for read
---------------------------------------------------
        +     +                      "r+"   open for update (reading and writing)
        +     +     +                "w+"   truncate/create for update
        +     +           +          "a+"   open or create for update - writes seek to EOF
        +                 +          "a+"
---------------------------------------------------
  +           +                      "wb"   All same as above, but in binary mode
  +           +           +          "ab"
  +                       +          "ab"
  +           +     +                "wb"
  +     +                            "rb"
---------------------------------------------------
  +     +     +                      "r+b"
  +     +     +     +                "w+b"
  +     +     +           +          "a+b"
  +     +                 +          "a+b"

关于c++ - 在 C++ 中写入现有的空格二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19597118/

相关文章:

c++ - 如何使用c++实时数据增加gnuplot的绘图频率?

c++ - 为什么编译器在 printf 中将 char 转换为 int?

c++ - QF模式匹配算法伪代码转c代码

c++ - 使用 WideCharToMultibyte 时如何删除控制字符

c# - 将 char * 参数传递给 C# 函数

java - 在 5000 多个文本文件中搜索特定字符串。

c++ - 解决标识符 "xxx"is undefined

c# - 将整数发送到 Android 后台应用程序

c++ - 如何访问相同特征C++的不同特征专长?

c++ - 为什么要提供两个get函数