From bc974067cbbc23a165f94fea351d55f7d92908a0 Mon Sep 17 00:00:00 2001 From: aortigos Date: Mon, 29 Sep 2025 07:25:49 +0200 Subject: [PATCH] New function for main loop --- ex04/main.cpp | 89 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 55 insertions(+), 34 deletions(-) diff --git a/ex04/main.cpp b/ex04/main.cpp index f86326e..a3913a3 100644 --- a/ex04/main.cpp +++ b/ex04/main.cpp @@ -6,13 +6,31 @@ /* By: aortigos #include +void replaceAndWrite(std::ifstream &infile, std::ofstream &outfile, + const std::string &s1, const std::string &s2) +{ + std::string line; + + line = ""; + while (std::getline(infile, line)) { + size_t pos = 0; + while ((pos = line.find(s1, pos)) != std::string::npos) + { + line.erase(pos, s1.length()); + line.insert(pos, s2); + pos += s2.length(); + } + outfile << line << std::endl; + } +} + int main(int argc, char **argv) { std::string filename; @@ -20,41 +38,44 @@ int main(int argc, char **argv) std::string s2; std::string line; - if (argc == 4) + if (argc != 4) { - filename = argv[1]; - s1 = argv[2]; - s2 = argv[3]; - line = ""; - - std::ifstream infile(filename.c_str(), std::ifstream::in); - if (!infile.is_open()) - { - std::cout << "Ha ocurrido un error en el infile" << std::endl; - return (1); - } - - std::ofstream outfile((filename + ".replace").c_str()); - if(!outfile.is_open()) - { - std::cout << "Hubo un error en el outfile" << std::endl; - return (1); - } - - while (std::getline(infile, line)) { - size_t pos = 0; - while ((pos = line.find(s1, pos)) != std::string::npos) - { - line.erase(pos, s1.length()); - line.insert(pos, s2); - pos += s2.length(); - } - outfile << line << std::endl; - } - infile.close(); - outfile.close(); - } else { std::cout << "Uso: ./sed " << std::endl; + return (1); } + filename = argv[1]; + s1 = argv[2]; + s2 = argv[3]; + line = ""; + + // Comprobamos que s1 no sea un string vacío + if (s1.empty()) { + std::cout << "s1 no puede estar vacío" << std::endl; + return (1); + } + + // Intentamos abrir el input + std::ifstream infile(filename.c_str(), std::ifstream::in); + if (!infile.is_open()) + { + std::cout << "Ha ocurrido un error en el infile" << std::endl; + return (1); + } + + // Intentamos abrir el output + std::ofstream outfile((filename + ".replace").c_str()); + if(!outfile.is_open()) + { + std::cout << "Hubo un error en el outfile" << std::endl; + return (1); + } + + // Ejecutamos el bucle para reemplazar + replaceAndWrite(infile, outfile, s1, s2); + + // Cerramos los archivos + infile.close(); + outfile.close(); + return (0); }