如何在c ++中打开文件而又不删除文件内容且不附加文件? [英] How can I open a file in c++, without erasing its contents and not append it?
问题描述
我试图找到一种方法,可以在不读取整个文件的情况下编辑二进制文件中的内容.
I am trying to find a way using which I can Edit the contents in a binary file, without reading the whole file.
假设这是我的文件
abdde
我想做到
abcde
我尝试了以下操作:- 尝试1)
I tried following:- Attempt 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'
And if I just try to replace the 1st byte of the file, which is 'a' with 'h'
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
我该怎么办?操作系统甚至可能允许程序在任何时候自行编辑文件吗?
What do I do? Is it even possible for the OS to allow a program to edit a file at any point own its own?
推荐答案
std::ios::app
表示光标在每次写操作之前都放在文件的末尾.寻求没有效果.
std::ios::app
means the cursor is put at the end of the file before every write. Seeking has no effect.
同时,对于输出流,std::ios::binary
默认进入截断"模式.
Meanwhile, std::ios::binary
goes into "truncation" mode by default for an output stream.
您都不想要这些.
我建议std::ios::out | std::ios::in
,也许只是创建一个std::fstream fs(path, std::ios::binary)
而不是使用std::ofstream
.
I suggest std::ios::out | std::ios::in
, perhaps by just creating a std::fstream fs(path, std::ios::binary)
rather than using an std::ofstream
.
是的,这有点令人困惑.
Yes, it's a bit confusing.
(参考)
这篇关于如何在c ++中打开文件而又不删除文件内容且不附加文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!