How to rewrite only part of a file in C ++

I want to make changes to the middle of a text file using C ++ without changing the rest of the file. How can i do this?

+7
c ++ text-files
source share
3 answers

If the replacement string is the same length, you can make changes in place. If the replacement string is shorter, you can fill it with spaces of zero width or similar to make it the same number of bytes, and make changes to the place. If the replacement string is longer, there is simply not enough space unless you transfer all the remaining data.

+8
source share

Use std :: fstream .

The simplest std :: stream will not work. This will truncate your file (unless you use the std :: ios_base :: app option, but that's not what you want).

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); 
+12
source share

As a rule, open the file for reading in text mode, read the line after the line to the place you want to change when reading the lines, write them in the second text file that you opened for writing. In the place for the change, write new data in the second file. Then continue reading / writing the file to the end.

0
source share

All Articles