【发布时间】: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
我该怎么办?操作系统甚至有可能允许程序在任何时候编辑自己的文件吗?
【问题讨论】:
-
this
filebuf::openreference 中的表格可能会有所帮助。它告诉我你应该使用in|outopen-mode。
标签: c++ operating-system filesystems fstream ifstream