fstream替换文件的一部分 [英] fstream replace portion of a file

查看:187
本文介绍了fstream替换文件的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我做

fstream someFile("something.dat", ios::binary|ios::out);
someFile.seekp(someLocation, ios::beg);
someFile.write(someData, 100);

似乎将整个文件替换为100个字节,而不是仅替换适当的100个字节如果我指定了ios :: trunc。有没有可移植的方式,不能截断文件?

It seems to replace the entire file with those 100 bytes instead of replacing only the appropriate 100 bytes, as if I had specified ios::trunc. Is there a portable way to not have it truncate the file?

编辑:添加ios :: in似乎做的伎俩,为什么这是否是必需的,是标准行为吗?

adding ios::in seems to do the trick, by why is this required, and is that standard behavior?

编辑#2:我不想附加到现有文件。

Edit #2: I am not trying to append to the existing file. I need to replace the 100 bytes while leaving the rest unaffected.

推荐答案

你想要的append标志,ios :: app,if您要在文件末尾写入。

You want the append flag, ios::app, if you want to write at the end of the file.

要在文件中间任意做,您需要寻找到正确的地方。你可以通过打开文件输入和输出,但如果我是你创建一个临时文件,复制输入到标记,写入您的新数据,复制剩余的EOF,关闭文件和替换以前版本与临时文件。这称为主文件更新。

To do it somewhere arbitrarily in the middle of the file, you need to seek to the right place. You CAN do this by opening the file for in and out, but if I were you I'd create a temp file, copy input up to mark, write your new data, copy the rest to EOF, close the files and replace the previous version with the temp file. This is called a "Master File update".

这篇关于fstream替换文件的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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