如何在 c++ 中仅覆盖文件的一部分

发布于 2024-08-27 00:19:38 字数 52 浏览 2 评论 0原文

我想使用 c++ 对文本文件的中间进行修改,而不更改文件的其余部分。我怎样才能做到这一点?

I want to make modifications to the middle of a text file using c++, without altering the rest of the file. How can I do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

奢华的一滴泪 2024-09-03 00:19:38

使用std::fstream

更简单的 std::ofstream 不起作用。它会截断您的文件(除非您使用选项 std::ios_base::app ,这无论如何都不是您想要的)。

std::fstream s(my_file_path); // use option std::ios_base::binary if necessary
s.seekp(position_of_data_to_overwrite, std::ios_base::beg);
s.write(my_data, size_of_data_to_overwrite);

Use std::fstream.

The simpler std::ofstream would not work. It would truncate your file (unless you use option std::ios_base::app, which is not what you want anyway).

std::fstream s(my_file_path); // use option std::ios_base::binary if necessary
s.seekp(position_of_data_to_overwrite, std::ios_base::beg);
s.write(my_data, size_of_data_to_overwrite);
有深☉意 2024-09-03 00:19:38

如果替换字符串的长度相同,则可以就地进行更改。如果替换字符串较短,您可以用零宽度空格或类似的内容填充它,以使其字节数相同,并就地进行更改。如果替换字符串较长,则没有足够的空间,除非您首先移动所有剩余数据。

If the replacement string is the same length, you can make the change in place. If the replacement string is shorter, you may be able to pad it with zero-width spaces or similar to make it the same number of bytes, and make the change in place. If the replacement string is longer, there just isn't enough room unless you first move all remaining data.

冰雪之触 2024-09-03 00:19:38

一般来说,以文本模式打开文件进行读取,逐行读取,直到要更改的位置,在读取行的同时,将它们写入您打开的第二个文本文件中进行写入。在更改的地方,将新数据写入第二个文件。然后继续读/写文件直到结束。

Generally, open the file for reading in text mode, read line after line until the place you want to change, while reading the lines, write them in a second text file you opened for writing. At the place for change, write to the second file the new data. Then continue the read/write of the file to its end.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文