How to overwrite only part of a file in c++

2019-01-07 23:10发布

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?

3条回答
Animai°情兽
2楼-- · 2019-01-07 23:13

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.

查看更多
可以哭但决不认输i
3楼-- · 2019-01-07 23:25

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.

查看更多
Root(大扎)
4楼-- · 2019-01-07 23:26

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);
查看更多
登录 后发表回答