From 006ac94c7f7ab5f6d2d4668a0d819f0945ada068 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kha=C3=AFs=20COLIN?= Date: Mon, 12 May 2025 14:37:53 +0200 Subject: [PATCH] feat(ex04): it works --- ex04/.gitignore | 3 +++ ex04/Makefile | 38 +++++++++++++++++++++++++++++++++ ex04/main.cpp | 56 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 97 insertions(+) create mode 100644 ex04/.gitignore create mode 100644 ex04/Makefile create mode 100644 ex04/main.cpp diff --git a/ex04/.gitignore b/ex04/.gitignore new file mode 100644 index 0000000..485d676 --- /dev/null +++ b/ex04/.gitignore @@ -0,0 +1,3 @@ +ex04 +*.txt +*.replace diff --git a/ex04/Makefile b/ex04/Makefile new file mode 100644 index 0000000..9d903fe --- /dev/null +++ b/ex04/Makefile @@ -0,0 +1,38 @@ +NAME = ex04 +ifeq ($(CPPFLAGS),) + CPPFLAGS = -Wall -Wextra -Werror -std=c++98 -g +endif +ifeq ($(CXX),) + CXX = c++ +endif +# g++ is the default on 42 computers +ifeq ($(CXX),g++) + CXX = c++ +endif +srcs = \ + +main_objs = main.o $(srcs:.cpp=.o) +all_objs = $(main_objs) +deps = $(all_objs:.o=.d) + +all: $(NAME) + +-include $(deps) + +$(NAME): $(main_objs) + $(CXX) $(CPPFLAGS) -o $@ $^ + +%.o: %.cpp + $(CXX) -c $(CPPFLAGS) -o $*.o $*.cpp + $(CXX) -MM $(CPPFLAGS) -MT $*.o $*.cpp > $*.d + +clean: + find . -name '*.o' -print -delete + find . -name '*.d' -print -delete + +fclean: clean + rm -f $(NAME) + +re: + +make fclean + +make all diff --git a/ex04/main.cpp b/ex04/main.cpp new file mode 100644 index 0000000..b221000 --- /dev/null +++ b/ex04/main.cpp @@ -0,0 +1,56 @@ +#include +#include +#include +#include + +int main(int argc, char *argv[]) { + if (argc != 4) { + std::cerr << "Usage: " << argv[0] << " " << 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; +}