如何在 c++ 中仅覆盖文件的一部分
我想使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用std::fstream。
更简单的 std::ofstream 不起作用。它会截断您的文件(除非您使用选项 std::ios_base::app ,这无论如何都不是您想要的)。
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).
如果替换字符串的长度相同,则可以就地进行更改。如果替换字符串较短,您可以用零宽度空格或类似的内容填充它,以使其字节数相同,并就地进行更改。如果替换字符串较长,则没有足够的空间,除非您首先移动所有剩余数据。
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.
一般来说,以文本模式打开文件进行读取,逐行读取,直到要更改的位置,在读取行的同时,将它们写入您打开的第二个文本文件中进行写入。在更改的地方,将新数据写入第二个文件。然后继续读/写文件直到结束。
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.