首页 > 解决方案 > 如何在 C++ 中打开文件,而不删除其内容而不附加它?

问题描述

我正在尝试找到一种方法来编辑二进制文件中的内容,而无需读取整个文件。

假设这是我的文件

abdde

我想成功

abcde

我尝试了以下操作:-尝试1)

ofstream f("binfile", ios::binary);
if(f.is_open()){
  char d[]={'c'};
  f.seekp(2,ios::beg);
  f.write(d, 1);
  f.close();
}
//the file get erased

输出:

**c

尝试 2)

ofstream f("binfile", ios::binary | ios::app);
if(f.is_open()){
  char d[]={'c'};
  f.seekp(2,ios::beg);
  f.write(d, 1);
  f.close();
}
//the file simple gets append seekp() does nothing

输出:

abddec

尝试 3)

ofstream f("binfile", ios::binary | ios::app);
if(f.is_open()){
  char d[]={'c'};
  f.seekp(2);
  f.write(d, 1);
  f.close();
}
//same as before the file simple gets append seekp() does nothing

输出:

abddec

如果我只是尝试用 'h' 替换文件的第一个字节,即 'a'

ofstream f("binfile", ios::binary);
if(f.is_open()){
  char d[]={'c'};
  f.seekp(ios::beg);
  f.write(d, 1);
  f.close();
}
//file is erased

输出:

h

我该怎么办?操作系统甚至有可能允许程序在任何时候编辑自己的文件吗?

标签: c++operating-systemfilesystemsfstreamifstream

解决方案


std::ios::app表示在每次写入之前将光标放在文件末尾。寻找没有效果。

同时,std::ios::binary默认情况下,输出流进入“截断”模式。

你两个都不想要。

我建议std::ios::out | std::ios::in,也许只是创建一个std::fstream fs(path, std::ios::binary)而不是使用一个std::ofstream.

是的,这有点令人困惑。

参考


推荐阅读