using streambuf when working with files
Hi, I'm writing a simple program that performs a simple text substituion.
Program needs to replace text in a file.
I manage to do something like this:
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <streambuf>
using namespace std;
int main()
{
string s;
string::size_type ind;
ifstream in ("in.txt", ios_base::in);
ofstream out("out.txt", ios_base::out);
while (getline(in ,s))
{
ind = s.find("second");
if (ind == string::npos)
{
out<< s<<endl;
continue;
}
else
{
s.replace(ind,sizeof("second")-1,"rep");
out<<s<<endl;
}
}
}
I test it with a simle file in.txt:
This is first sentence.
This is second sentence.
This is third sentence.
and result is:
This is first sentence.
This is rep sentence.
This is third sentence.
As you can see my program create another file named out.txt which contains replacement.
I want changes to be made in original file.
Sure, I can add something like this:
Code:
out.close();
in.close();
out.open("in.txt",ios_base::out);
in.open("out.txt", ios_base::in);
out<<in.rdbuf();
but this would be very inefficient way to handle this plus there is a new (unwanted) file out.txt.
My question is how to perform this task with only one file in a more efficient way.
My idea is to:
1. open file (ifstream)
2. store contents in a buffer
3. close file
4. examine buffer (possible with the same while loop)
5. made changes
6. open file (ofstream)
7. overwrite it with new contnts.
HI don't know much about strembufs and if you can post some code to understand how this would be done.
My attempt was something like this:
Code:
...
ifstream in ("in.txt", ios_base::in);
streambuf* pbuf = in.rdbuf();
...
but question is how to use getline in that case?
I hope you can help me. The best help would be to post some code, because it's the best way to learn new things (at least, for me)
I realize this can be done in another way, for instance by using vector to act like buffer
Code:
string s;
string::size_type ind;
ifstream in ("in.txt", ios_base::in);//open file
vector<string> v;//sentences will be stored in vector (buffer)
while (getline(in ,s))
{
ind = s.find("second");
if (ind == string::npos)
{
v.push_back(s);
continue;
}
else
{
s.replace(ind,sizeof("second")-1,"rep");
v.push_back(s);
}
}
in.close();//close file
vector<string>::const_iterator it;//vector iterator
ofstream out ("in.txt",ios_base::out);
for (it = v.begin(); it != v.end(); ++it)
out<<*it<<endl;//write to file
out.close();//close file
But, I'd like to see solution using streambuf, if I'm not asking too much
Thanks