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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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();
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();
#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;
}
#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
// 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;
}
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.
Then you can write to the text file, but writeing the std::vector<string> to it.