c++ - 如何在 C++ 中打开文件而不删除其内容且不附加它?

标签 c++ operating-system filesystems fstream ifstream

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

假设这是我的文件

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

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

最佳答案

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

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

这些你都不想要。

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

是的,这有点令人困惑。

( Reference )

关于c++ - 如何在 C++ 中打开文件而不删除其内容且不附加它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59059486/

相关文章:

C++ EOF Getline 错误

c++ - C++ 模板的编译器错误表明这不是结构体的成员

compiler-construction - 激活记录在内存中是连续的吗?

python - 读取 Windows 文件而不阻止其他进程写入该文件

linux - 商品 Linux 存储场的最佳分布式文件系统

c++ - 如何清除使用用户定义比较的 `priority_queue`?

c++ - C函数尽可能多地使用寄存器

c - 添加到C中数组的地址

c - 操作系统的低级指针处理

linux - 网络服务器无法打开包含 % 的文件