简体   繁体   English

覆盖文件中的字节而不清除它

[英]Overwrite byte in file without clearing it

How to overwrite a byte in a file without clearing the entire file?如何在不清除整个文件的情况下覆盖文件中的一个字节? Note that I don't want to insert additional bytes but rather overwrite a byte at a certain offset.请注意,我不想插入额外的字节,而是在某个偏移量处覆盖一个字节。

I have tried the following code to write a byte at some offset.我尝试了以下代码在某个偏移量处写入一个字节。 However this clears everything after the specified offset which is not what I want.但是,这会清除指定偏移量之后的所有内容,这不是我想要的。

#include <fstream>

int main()
{
    std::ofstream ofs {"foo", std::ios::binary};
    ofs.seekp(0x2);
    ofs.put(0x7);
}

In general people on SO seem to suggest reading the entire file then changing it in memory and then writing it out again.一般来说,SO 上的人似乎建议读取整个文件,然后在 memory 中更改它,然后再写出来。 However that seems too much work to just change a single byte.然而,仅仅改变一个字节似乎工作量太大。

Is it not possible to overwrite a single byte in-place?就地覆盖单个字节是不可能的吗?

It's perfectly possible (in fact common) to update a file, provided you don't want to insert any new bytes before the current end of file.如果您不想在当前文件末尾之前插入任何新字节,则更新文件是完全可能的(事实上很常见)。

Change to this改成这样

std::ofstream ofs {"foo", std::ios::in|std::ios::out|std::ios::binary};

However this will fail if the file does not exist, but it sounds like that is not a concern.但是,如果文件不存在,这将失败,但听起来这不是问题。

By just using std::ios::binary (which the ofstream constructor adjusts to std::ios::out|std::ios::binary ) you destroyed the file contents.通过仅使用std::ios::binaryofstream构造函数将其调整为std::ios::out|std::ios::binary ),您破坏了文件内容。 Your code then took advantage of a little known feature of C/C++ I/O which is that it is possible to seek beyond the end of a file.然后,您的代码利用了 C/C++ I/O 的一个鲜为人知的特性,即可以在文件末尾之外进行查找。 If any bytes are written when the file is in this state the gap between the file end and the current position is filled with zeros.如果文件在这个 state 中时写入了任何字节,则文件末尾和当前 position 之间的间隙用零填充。

Here's a reference on what the different file modes do.这是有关不同文件模式的作用的参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM