feat(ex04): it works

This commit is contained in:
Khaïs COLIN 2025-05-12 14:37:53 +02:00
parent 28784b50f0
commit 006ac94c7f
Signed by: logistic-bot
SSH key fingerprint: SHA256:RlpiqKeXpcPFZZ4y9Ou4xi2M8OhRJovIwDlbCaMsuAo
3 changed files with 97 additions and 0 deletions

3
ex04/.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
ex04
*.txt
*.replace

38
ex04/Makefile Normal file
View file

@ -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

56
ex04/main.cpp Normal file
View file

@ -0,0 +1,56 @@
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
int main(int argc, char *argv[]) {
if (argc != 4) {
std::cerr << "Usage: " << argv[0] << " <filename> <s1> <s2>" << 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;
}