我试图用二进制文件写一些文件,我需要覆盖文件内容,如何过度写入而不是插入

时间:2012-04-10 04:25:54

标签: c++ file binaryfiles ofstream

我正在用C ++编写一个二进制文件,在那里我遍历到一个特定的位置,需要用新的内容覆盖内容。我知道整数大小的内容,所以我跟踪位置并重写它。好像是,ofstream write函数插入或追加变量。有没有办法,我可以写,而不是附加或插入文件

  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,值3

3 个答案:

答案 0 :(得分:0)

相关标志是截断

  

(truncate)丢弃任何当前内容,假设长度为   打开时为零。

答案 1 :(得分:0)

您需要在开放参数中添加std::ios::trunc,如:

std::ofstream file_write(filename, std::ios::out|std::ios::binary|std::ios::trunc);

这将截断文件,丢弃任何现有内容。

答案 2 :(得分:0)

我整理出来了。我们需要使用fstream而不是ofstream。谢谢你帮助大家