Arne
Arne

Reputation: 20217

Write to the start of a textfile in c++

I was looking for an easy way to write something into the first line of an already existing textfile. I tried using ofstream like this:

ofstream textFileWriter("Data/...txt");
if (textFileWriter.is_open())
{
    textFileWriter << "HEADER: stuffstuff";
}

But it would delete everything which used to be in that file, even though the ofstream wasn't constructed with std::ofstream::trunc. I cannot use std::ofstream::app, since it is important to write into the first line.

Copying the whole textfile into a vector which has the line already and then writing it back would be my last option, but something I would really like to avoid, since the textfiles are quite large.

Upvotes: 0

Views: 147

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409384

You can't simply "append" to the beginning of a file.

The common solution is to open a new (temporary) file, write your new header, write the rest of the original file to the temporary file, and then "rename" (using the OS system calls) the temporary file as the original file.

Or as you say in your question, read the original file into an in-memory buffer (e.g. a vector) and do the modification in that buffer, and then write the buffer to the file.

Upvotes: 2

Related Questions