New function for main loop

This commit is contained in:
2025-09-29 07:25:49 +02:00
parent 7dad10844e
commit bc974067cb

View File

@@ -6,41 +6,19 @@
/* By: aortigos <aortigos@student.42malaga.com +#+ +:+ +#+ */ /* By: aortigos <aortigos@student.42malaga.com +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2025/09/06 14:44:18 by aortigos #+# #+# */ /* Created: 2025/09/06 14:44:18 by aortigos #+# #+# */
/* Updated: 2025/09/14 13:50:49 by aortigos ### ########.fr */ /* Updated: 2025/09/29 07:24:35 by aortigos ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
#include <iostream> #include <iostream>
#include <fstream> #include <fstream>
int main(int argc, char **argv) void replaceAndWrite(std::ifstream &infile, std::ofstream &outfile,
const std::string &s1, const std::string &s2)
{ {
std::string filename;
std::string s1;
std::string s2;
std::string line; std::string line;
if (argc == 4)
{
filename = argv[1];
s1 = argv[2];
s2 = argv[3];
line = ""; 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)) { while (std::getline(infile, line)) {
size_t pos = 0; size_t pos = 0;
while ((pos = line.find(s1, pos)) != std::string::npos) while ((pos = line.find(s1, pos)) != std::string::npos)
@@ -51,10 +29,53 @@ int main(int argc, char **argv)
} }
outfile << line << std::endl; outfile << line << std::endl;
} }
}
int main(int argc, char **argv)
{
std::string filename;
std::string s1;
std::string s2;
std::string line;
if (argc != 4)
{
std::cout << "Uso: ./sed <filename> <s1> <s2>" << 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(); infile.close();
outfile.close(); outfile.close();
} else {
std::cout << "Uso: ./sed <filename> <s1> <s2>" << std::endl;
}
return (0); return (0);
} }