我正在写一个二进制文件在C++中,我遍历到一个特定的位置,用新的内容写下内容。我知道整数大小的内容,所以我跟踪了位置并重写了它。好像,流写入函数插入或追加变量。有没有一种方法,在那里我可以在写,而不是附加或在文件中插入我想写一些二进制文件,我需要覆盖文件内容,如何写而不是插入
long word = sizeof(int) + sizeof(long) + sizeof(long);
std::ofstream file_write(filename, std::ios::out|std::ios::binary);
file_write.seekp(word);
long pos = file_write.tellp();
file_write.write((char *)&some_integer,sizeof(int));
file_write.close()
//some other location
file_write.seekp(pos);
file_write.write((char *)&some_other_integer,sizeof(int));
//这里some_integer应该结束了写some_other_integer。有没有办法做到这一点?
这将是像
值1,值2,值3
我也许能值5
然后更换价值2它应该看起来像
值1,值5, value3
如果您只是想覆盖文件中的单个值,那么您显示的代码将起作用。你确定你展示的代码实际上代表了你正在使用的代码吗?你确定代码不工作吗? – 2012-04-10 05:00:07
对不起,我想它是这样工作的,你是对的,我感到困惑,有一个不同的问题。很抱歉,发贴者,有没有办法删除帖子? – howtechstuffworks 2012-04-10 05:23:12
嘿埃里克,它不那样工作。我删除之前的信息,并在它之后推送信息。请参阅此链接了解更多代码。 http://stackoverflow.com/questions/10096196/cant-over-write-on-a-specific-location-on-a-file-over-write-on-a-specific-loca – howtechstuffworks 2012-04-10 21:47:48