Alex Rivera | Logout

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

Asked 2010-03-27T17:49:20.900
12

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?

Edit
Report

1 Answer

25

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);
answered 2012-01-18T07:56:01.963

Your Answer