Link to home
Start Free TrialLog in
Avatar of sorinv
sorinv

asked on

Insert a line in a text file using fstream

Hi,

I'm new to C++. I have an application that has to insert a line in a text file (if possible without creating another file).

I have to use STL and fstream.

Any ideas how to do it?

Thanks,
Sorin
ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Axter
You can use std::vector<string> to read each line in the text file.  While you're reading the line into the std::vector<string>, you can insert a line.
Then you can write to the text file, but writeing the std::vector<string> to it.
When you read it, use the global getline function to read the text file line by line.
Something like the following:
     vector<string> lines;
     fstream in("test2.cpp");
     while (!in.eof())
     {
          string line;
          getline(in,line);
          lines.push_back(line);
     }
     in.close();
Avatar of nietod
nietod

#include <fstream>
#include <vector>
#include <string>

using namespace std;

int main()
{
   vector<string> FilDat;
   fstream Fil("filename.txt");

   // Read in all the data
  while (!Fil.eof()))
  {
     string Lin;

     getline(Fil,Lin);
     FilDat.push_back(Lin);
  }

  // Insert a new line after the 3rd line.
  FilDat.insert(FilDat.begin()+2,"This is a new line");

  // Write out the data.
  const int LinCnt = FilDat.size();  

  Fil.seekp(0);
  for (int i = 0; i < LinCnt; ++i)
      Fil << FilDat[i] << endl;

   return 0;
}
Avatar of sorinv

ASKER

Thanks. I thought it would be this way, but I hopped you guys would have come with a better solution. Thanks nayway for clarifying the things for me.
Every word processor in the world works in one of these ways.   Most are now memory based, readig all the file in and manipulating it in memory, but when memory was tight they sed to be mostly file based.