std::ofstream ofs;
ofs << "Hello, world!" << endl;
Now I want to modify the contents of ofs
to "Hello, money!"
before writting to disk.
How can I implement it?
The std::endl
IO manipulator will flush the content of the stream buffer, so you will have to change it into a '\n'
if you later want to process the stream before its content gets flushed.
Also, under the assumption that the reason you actually want to do this is because you need to manipulate the string which is going to be written after formatting, I shall make you aware of the fact that you can use an std::ostringstream
to exploit the functionality of formatted streaming and gather the result into a string, which you can then manipulate and normally write to a file.
If this was obvious information for you and your use case is more complex, then you will have to write your own stream buffer, as pointed out by @MatsPetersson.