How to insert text at the beginning of a file without overwriting any existing data?

For example the content of a file is:
Line 1
Line 2
Line 3
and I wanna insert Line 0 by scrolling the existing data.
So that the content changes to:
Line 0
Line 1
Line 2
Line 3

I usually do so by reading all the content of the file and storing it temporarily as follow...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <fstream>
int main()
{
    std::string Line0="Line 0",//the line that should be inserted at the beginning of the file
                          temp,//to read lines one by one
                   FileContent;//that will be the new content for the file
    std::fstream File("File.txt");
    FileContent=Line0; //insert line0 first
    while(getline(File, temp))FileContent+="\n"+temp; //add the content of the file after line0
    File.close();
    File.open("File.txt", std::ios::out); //reopen the file for output operation
    File<<FileContent;//print the new content
    File.close();
}

But this method might not be good with heavy files. So, what is the typical way for doing that?
Maybe you can check first how big the file is and how much memory is available.
According to the information you can stick with the above approach or for huge files you create a second file, write the new line into it and then read the old file line by line and rite to the new file. Finally you can delete the old file.
Topic archived. No new replies allowed.