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

时间:2022-06-29 00:05:04

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?

我想使用c++对文本文件的中间部分进行修改,而不改变文件的其余部分。我怎么做呢?

3 个解决方案

#1


8  

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.

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

#2


12  

Use std::fstream.

使用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::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);

#3


0  

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.

通常,在文本模式下打开文件,一行一行地读,直到你想要改变的地方,在阅读的时候,把它们写在你打开的第二个文本文件中。在更改的地方,将新数据写入第二个文件。然后继续文件的读/写,直到文件结束。

#1


8  

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.

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

#2


12  

Use std::fstream.

使用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::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);

#3


0  

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.

通常,在文本模式下打开文件,一行一行地读,直到你想要改变的地方,在阅读的时候,把它们写在你打开的第二个文本文件中。在更改的地方,将新数据写入第二个文件。然后继续文件的读/写,直到文件结束。