写入现有二进制文件c的中间++ [英] Write to the middle of an existing binary file c++
问题描述
我试图打开一个只写一个二进制文件,但不删除的内容。但我不希望写入EOF。我想要写在文件中的特定位置。
I'm trying to open a binary file for writing without erasing the content. But I do not want to write to eof. I want to write to a specific position in file.
下面是豆蔻例如:
ofstream out("test.txt", ios::binary | ios::app);
for(int i = 0; i < 100; i++)
out.put('_');
out.write("Hallo", 5);
out.close();
ofstream out2("test.txt", ios::binary | ios::app);
out2.seekp(10);
out2.write("Welt", 4);
out2.close();
如果使用的应用程序,寻求不起作用。如果不使用的应用程序打开文件擦除数据。是否有人知道答案?
If using app, seek doesn't work. If not using app opening file erases data. Does anybody know an answer?
推荐答案
尝试 seekp
的第二个重载,它允许您提供一个偏移量和的方向的,这可能会在你的情况下开始时的文件(即的ios_base ::求
)。当然,这可以让你知道你在做什么,你想要做的是覆盖现有的字符数。
try the second overload of seekp
, which allows you to provide an offset and a direction, this could be begining of file in your case (i.e. ios_base::beg
). This of course assumes you know what you are doing and all you want to do is overwrite an existing number of characters.
编辑:这是完全的例子:
here is fully working example:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
{
ofstream out("test.txt", ios::binary);
for(int i = 0; i < 100; i++)
out.put('_');
out.write("Hallo", 5);
}
{
fstream out2("test.txt", ios::binary | ios::out | ios::in);
out2.seekp(10, ios::beg);
out2.write("Welt", 4);
}
}
这篇关于写入现有二进制文件c的中间++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!