--- /dev/null
+#include <string>
+#include <fstream>
+#include <iostream>
+
+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();
+}
+