【问题标题】:How can I open a file in c++, without erasing its contents and not append it?如何在 C++ 中打开文件,而不删除其内容而不附加它?
【发布时间】:2020-03-22 09:03:06
【问题描述】:

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

假设这是我的文件

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-system filesystems fstream ifstream


【解决方案1】:

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

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

这两个你都不想要。

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

是的,这有点令人困惑。

(Reference)

【讨论】:

  • 是的,fstream f(path", ios::binary|ios::in|ios::out); 有效:-)
猜你喜欢
  • 2019-02-15
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 2011-09-14
  • 2020-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多