Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

text-files

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?

like image 765
neuromancer Avatar asked Mar 27 '10 17:03

neuromancer


1 Answers

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);
like image 87
ZunTzu Avatar answered Sep 23 '22 22:09

ZunTzu