This is very funny. I just wrote exactly this last night. I did what was recommended a few posts above: read the whole file into a container, modify the exact line, and write back out. If you use standard algorithms, there is really not much to it. I just typed in what I remember, I have no idea if this actually compiles, but hopefully you get the idea.
Code:
#include <iostream>
#include <fstream>
#include <list>
#include <string>
#include <algorithm>
using namespace std;
// You need a class called line that overloads the operator>> and
// operator<<:
class Line {
public:
std::string ln_;
Line(string& in) { ln_ = in; }
friend istream& operator>>(istream& s, Line& l)
{
return getline(s,l.ln);
}
friend ostream& operator<<(istream& s, Line& l)
{
return s<<l.ln<<endl;
}
};
// For reading in the file, you can do something very neat with a
// standard algorithm and a functor:
// define a functor somewhere that stores the line to look for,
// and what to replace it with. Basically you return the input line
// unless it matches what you are looking for, when you return
// the other string, ie:
class ModifyLine {
string look_for;
string relpace_with;
public:
ModifyLine(string& lf, string& rw)
{
look_for = lf;
replace_with = rw;
}
void operator()(Line& l) const
{
if ( l.ln == look_for )
return Line(replace_with);
else return l;
}
};
int main()
{
// code somewhere:
ifstream fs;
fs.open("filename");
// a list of lines
list<Line> lines;
string lookfor; // you gotta fill this in
string replace_with; // you gotta fill this in
// transform file input according to ModifyLine, and store it in
// lst
transform( istream_iterator<Line>(fs), istream_iterator<Line>(), back_inserter(lst), ModifyLine(lookfor, replace_with));
// write it back out
ofstream of;
of.open("filename");
// another standard alogrithm!
copy( lst.begin(), lst.end(), ostream_iterator<Line>(of,"\n"));
// done...
return 0;
}