56 lines
1.4 KiB
C++
56 lines
1.4 KiB
C++
#include <cstring>
|
|
#include <fstream>
|
|
#include <iostream>
|
|
#include <string>
|
|
|
|
int main(int argc, char *argv[]) {
|
|
if (argc != 4) {
|
|
std::cerr << "Usage: " << argv[0] << " <filename> <s1> <s2>" << std::endl;
|
|
return 2;
|
|
}
|
|
|
|
std::string in_filename = argv[1];
|
|
std::string out_filename = in_filename + ".replace";
|
|
std::string s1 = argv[2];
|
|
std::string s2 = argv[3];
|
|
|
|
std::ifstream infile(in_filename.c_str(), std::ios::in);
|
|
|
|
if (!infile.is_open()) {
|
|
std::cerr << "Failed to open file " << in_filename << ": "
|
|
<< strerror(errno) << std::endl;
|
|
return 1;
|
|
}
|
|
|
|
std::ofstream outfile(out_filename.c_str());
|
|
|
|
if (!outfile.is_open()) {
|
|
std::cerr << "Failed to open file " << out_filename << ": "
|
|
<< strerror(errno) << std::endl;
|
|
return 1;
|
|
}
|
|
|
|
std::string line;
|
|
while (!infile.eof() && !infile.fail()) {
|
|
if (infile.fail()) {
|
|
std::cerr << "Failed to read from file " << in_filename << ": "
|
|
<< strerror(errno) << std::endl;
|
|
return 1;
|
|
}
|
|
std::getline(infile, line);
|
|
size_t pos = 0;
|
|
while (pos < line.length()) {
|
|
size_t offset = line.find(s1, pos);
|
|
outfile << line.substr(pos, offset - pos);
|
|
if (offset == std::string::npos) {
|
|
break;
|
|
}
|
|
outfile << s2;
|
|
pos = offset + s1.length();
|
|
}
|
|
if (!infile.eof() && !infile.fail())
|
|
outfile << std::endl;
|
|
}
|
|
|
|
return 0;
|
|
}
|