#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void)
{
string buff;
string filename("myfile.txt");
string text1("65");
string text2("87");
fstream file(filename.c_str());
Just a nit, but this should be:
if ( ! file )
or
if ( ! file.fail() )
(or even
if ( ! file.is_open() )
).
istream::good() has somewhat strange semantics, and I think
(although it's not 100% clear) that it could return false if the
file was empty. (In general, I've never found a use for
istream::good().)
{
cout << "Error : cannot open file " << filename << "\n";
return 1;
}
getline(file,buff);
And of course, you have to check that this succeeded if you
don't want to get into trouble later.
string::size_type pos=buff.find(text1);
if(pos==string::npos)
{
cout << "Error : could not find the string "
cout << text1 << " in file " << filename << "\n";
return 1;
}
buff.replace(buff.find(text1),text2.length(),text2.c_str());
cout << buff << "\n";
file.seekg(0);
Which is valid if, and only if, the change is in the first line.
Otherwise, you have to use a value returned by tellg().
(Logically, since you're going to write, you should probably use
seekp() as well. With a filebuf, it doesn't matter; the put and
get pointers are identical, but it's probably a good habit to
get into.)
Also, there's a very slight chance that getline encountered EOF,
and has set eofbit. If so, the next operation automatically
sets fail state; it's generally a good idea to clear the status
before seeking.
Note that if the replace changed the length of buff, you're now
in deep trouble.
file.close();
return 0;
}
any comment welcome. I could have a done a loop on the getline
until end of file, but ... I am not that kind.
It would help if we knew more about the context as to why the
original poster wanted to do this. I can think of three
different approaches, depending on the exact goals. If the
replacement string ever has a different length than the
original, he's going to have to copy. Otherwise, if it is a
question of replacing all x with y, where x and y are guaranteed
to have the same length, a loop with getline might be
appropriate, provided you do a tellg before each getline, so you
can successfully seekp to it. And if you really want random
access, you'll have to open the file in binary mode, and it will
probably only work if all of the records (lines) have the same
length.