用fstream和seekp替换二进制文件中的数据 [英] Replacing data in binary file with fstream and seekp

查看:60
本文介绍了用fstream和seekp替换二进制文件中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个方法来替换二进制文件中的指定字符串,它在我用seekp设置的位置之前写NULL,然后写该字符串并关闭流.我只想替换文件中的某些字节.在这段代码之前,我尝试了带有ios :: binary和ios :: out标志的ofstream.销毁文件中的所有数据有什么问题?在这段代码之前,我用ifstream实例打开文件以读取同一位置,以验证字符串中的第一个字节.我只对此发表评论以供参考.

I'm writing a method to replace a specified string from a binary file and it writes NULLs before the position I set with seekp, then writes the string and closes the stream. I only want to replace some bytes in the file. Before this piece of code I tried out with ofstream with ios::binary and ios::out flags. What's wrong to destroy all data in the file? Before this piece of code, I open the file with an instance of ifstream to read the same position verifyng the first byte in the string. I only comment this for information.

谢谢大家!

代码:

fstream ofs();
ofs.open(nomArchBin,ios::in | ios::out | ios::binary);

if (!ofs.good()) {
    cout << "...";
    return;
}

ofs.seekp(despEnArchivo,ios::beg);
char* registroChar = registroACadena(reg);
ofs.write(registroChar,cabecera.tamanioReg);

推荐答案

我知道这听起来很愚蠢,但这是打开文件进行写入的唯一方法而不是截断它是同时将其打开以供阅读:如果您真的在做 ios :: in |ios :: out |ios :: binary ,它应该可以工作.(但因为您显然重新输入了代码,并且没有复制/粘贴代码,所以我不知道这是否真的是您所做的.)

I know this sounds silly, but the only way to open a file for writing and not to truncate it is to open it for reading as well: if you're really doing ios::in | ios::out | ios::binary, it should work. (But since you obviously reentered the code, and didn't copy/paste it, I'm not sure if this is really what you did.)

寻找时必须注意的其他事项:

Other points you have to pay attention to when trying to seek:

  • 该文件必须以二进制模式打开,并带有"C"语言环境.(恕我直言,以二进制模式打开的文件应忽略语言环境,但这不是标准所说的.)
  • `seekg`和`seekp`具有相同的效果;使用任一更改对方的位置.
  • 允许搜索到任意位置的唯一功能是这两个论点都在寻求;一个论证形式只能用于寻求以前由柜员获得的职位.

这篇关于用fstream和seekp替换二进制文件中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆