From 35ef400bdf2f26f51896d825eb92741a08fdddaf Mon Sep 17 00:00:00 2001 From: Lukas Jiriste Date: Thu, 10 Oct 2024 19:44:25 +0200 Subject: [PATCH] Add solution to ex04 (without Makefile) --- ex04/main.cpp | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 ex04/main.cpp diff --git a/ex04/main.cpp b/ex04/main.cpp new file mode 100644 index 0000000..696626c --- /dev/null +++ b/ex04/main.cpp @@ -0,0 +1,67 @@ +#include +#include +#include + +int open_files(const char *filename, std::ifstream &old_file, std::ofstream &new_file) +{ + old_file.open(filename); + if (!old_file) + { + std::cout << "File " << filename << " not found!\n"; + return (1); + } + new_file.open(std::string(filename).append(".replace").c_str()); + if (!new_file) + { + std::cout << "File " << filename << ".replace could not be created!\n"; + old_file.close(); + return (1); + } + return (0); +} + +void rewrite_file(std::ifstream &old_file, std::ofstream &new_file, + std::string old_string, std::string new_string) +{ + std::string line; + size_t i; + size_t j; + + while (!old_file.eof()) + { + std::getline(old_file, line); + j = 0; + while (1) + { + i = line.find(old_string, j); + if (i == std::string::npos) + break ; + new_file << line.substr(j, i - j) << new_string; + j = i + old_string.size(); + } + new_file << line.substr(j) << '\n'; + } +} + +int main(int argc, char **argv) +{ + std::ifstream old_file; + std::ofstream new_file; + std::string old_str; + std::string new_str; + + if (argc != 4) + { + std::cout << "Wrong argument number, the correct usage is:\n" + "\tex04 FILENAME OLD_STRING NEW_STRING\n"; + return (1); + } + if (open_files(argv[1], old_file, new_file)) + return (2); + old_str = argv[2]; + new_str = argv[3]; + rewrite_file(old_file, new_file, old_str, new_str); + old_file.close(); + new_file.close(); +} + -- 2.30.2