3-7-6 读取文件并替换指定字符串

3.7-6 读取文件并替换指定字符串

源代码

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

string getData(string filename) throw(std::ifstream::failure)
{
std::ifstream streamReader(filename, std::ios::binary);
if (!streamReader.is_open())
throw std::ifstream::failure("file couldn't open");
streamReader.seekg(0, std::ios::end); // 游标移到文件结尾
unsigned filesize = streamReader.tellg(); // 获取游标当前位置 - 文件开始位置,此处为文件大小
char *_data = new char[filesize]; // 分配内存
streamReader.seekg(0, std::ios::beg); // 跳转回开始
streamReader.read(_data, filesize); // 读取文件
streamReader.close();
string data(_data);
delete[] _data;
return std::move(data);
}

std::string &replaceAll(std::string &context,
const std::string &from,
const std::string &to)
{
size_t lookHere = 0;
size_t foundHere;
while ((foundHere = context.find(from, lookHere)) != string::npos) // find from lookHere
{ // to avoid the string
context.replace(foundHere, from.size(), to); //"to" is the substr
lookHere = foundHere + to.size(); // of "from"
#ifdef SHOWREPLACE
cout << "stringNumber:" << foundHere << endl;
#endif
}
return context;
}

int main(int argc, char const *argv[])
{
if (argc < 4)
return -1;
try
{
string data = getData(argv[1]);
string from(argv[2]);
string to(argv[3]);
replaceAll(data, from, to);
cout << "The replace start:" << endl;
cout << data << endl
<< "the replace end" << endl;
}
catch (const std::exception &e)
{
std::cerr << e.what() << '\n';
}
return 0;
}

编译

g++ .\ReplaceFileTxt.cpp -o .\ReplaceFileTxt.exe -DSHOWREPLACE

使用

.\ReplaceFileTxt.exe Rparse.h size hello