问题描述
限时送ChatGPT账号..我正在尝试打开一个二进制文件进行写入而不删除内容.但我不想写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::beg
).这当然假设您知道自己在做什么,并且您想做的只是覆盖现有数量的字符.
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屋!
更多推荐
[db:关键词]
发布评论