Reputation:
I'm creating this simple program which would save me alot of time, but I'm kinda stuck.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> tempfile;
string line;
ifstream oldfile("old.lua");
if (oldfile.is_open())
{
while (oldfile.good())
{
getline(oldfile, line);
tempfile.push_back(line + "\n");
}
oldfile.close();
}
else
{
cout << "Error, can't find old.lua, make sure it's in the same directory as this program, and called old.lua" << endl;
}
ofstream newfile("new.lua");
if (newfile.is_open())
{
for (int i=0;i<tempfile.size();i++)
{
for (int x=0;x<tempfile[i].length();x++)
{
newfile << tempfile[i][x];
}
}
newfile.close();
}
return 0;
}
So, what this does now, is just copies a file. But I've tried to do it, so it changes fe. every "function" word to "def", I've tried everything and googled already, couldn't find anything useful enough, only thing I found was using sstream, but it didn't work after all, or maybe I'm just not skilled enough to do it, so if anyone could give me any tips or help, cause I really am stuck? :d
Upvotes: 0
Views: 3133
Reputation: 103693
boost has a replace all function, and it's much more efficient than the naive search-replace-repeat algorithm. This is what I would do:
std::string file_contents = LoadFileAsString("old.lua");
boost::replace_all(file_contents, "function", "def");
std::ofstream("new.lua") << file_contents;
LoadFileAsString is my own function that looks something like this:
std::string LoadFileAsString(const std::string & fn)
{
std::ifstream fin(fn.c_str());
if(!fin)
{
// throw exception
}
std::ostringstream oss;
oss << fin.rdbuf();
return oss.str();
}
http://www.boost.org/doc/libs/1_33_1/doc/html/replace_all.html
Upvotes: 1
Reputation: 361252
I didn't really understand your problem. I think you need to edit your post and ask it clearly.
But still you can do one major improvement in your code. You should be reading file using C++ stream, in this way:
while (getline(oldfile, line))
{
tempfile.push_back(line + "\n");
}
which is more idiomatic way of reading file using C++ stream!
Read this excellent blog by @Jerry Coffin (an SO user) :
http://coderscentral.blogspot.com/2011/03/reading-files.html
EDIT:
You want to find and replace text in your file, then see the accepted answer in this topic:
Upvotes: 1