1

I am trying to insert a line at the top of a txt file without deleting the entire file, is there a function or library that helps with this? I am using the fsream library but am unable to insert, only append using the ios::app feature for fstream.

Grice
  • 13
  • 3
  • There's only one way to do this, read the entire file into memory (into a string), insert the string you want to add to that string, and then write then whole string back out to the file. This is the only way to do it because file systems aren't designed for the kind of change you want to make. – john May 27 '20 at 08:16
  • 1
    Does this answer your question? [Adding text and lines to the beginning of a file (C++)](https://stackoverflow.com/questions/11108238/adding-text-and-lines-to-the-beginning-of-a-file-c) – Nicolas Dusart May 27 '20 at 08:16

1 Answers1

0

You can't insert data at the beginning of a file. You need to read the entire file into memory, insert data at the beginning, and write the entire thing back to disk. (I am assuming the file isn't too large).

Try this program.

#include <fstream>
#include <sstream>

int main()
{
    std::stringstream stream;
    stream << "First line\n"; // Add your line here!

    {
        std::ifstream file("filename.txt");
        stream << file.rdbuf();
    }

    std::fstream new_file("filename.txt", std::ios::out); 
    new_file << stream.rdbuf();

    return 0;
}
abhiarora
  • 9,743
  • 5
  • 32
  • 57
  • This works well! Do you know how big a given text file can be before this stops being a good method? – Grice May 27 '20 at 19:05