feat(ex04): it works
This commit is contained in:
parent
28784b50f0
commit
006ac94c7f
3 changed files with 97 additions and 0 deletions
56
ex04/main.cpp
Normal file
56
ex04/main.cpp
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
#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;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue