diff --git a/exercises/coreutils/cat/Makefile b/exercises/coreutils/cat/Makefile new file mode 100644 index 0000000..c7e8601 --- /dev/null +++ b/exercises/coreutils/cat/Makefile @@ -0,0 +1,19 @@ +CC := gcc +CFLAGS := -Wall -Wextra -pedantic -std=c11 -pthread -g +TARGET := cat +SRC := main.c +OBJS := $(SRC:.c=.o) + +.PHONY: all clean valgrind + +all: $(TARGET) + +$(TARGET): $(OBJS) + $(CC) $(CFLAGS) -o $@ $^ + +%.o: %.c + $(CC) $(CFLAGS) -c $< -o $@ + +clean: + rm -f $(TARGET) $(OBJS) + diff --git a/exercises/coreutils/cat/main.c b/exercises/coreutils/cat/main.c new file mode 100644 index 0000000..1df7f29 --- /dev/null +++ b/exercises/coreutils/cat/main.c @@ -0,0 +1,36 @@ +#include +#include +#include +#include + +#define BUFFER_SIZE 256 + +int main(int argc, char *argv[]) +{ + if (argc < 2) { + fprintf(stderr, "Usage: %s FILE...\n", argv[0]); + return EXIT_FAILURE; + } + + for (int i = 1; i < argc; i++) { + FILE *fp = fopen(argv[i], "r"); + if (fp == NULL) { + perror("fopen"); + return EXIT_FAILURE; + } + + // Read file and print on the stdout + size_t nread; + unsigned char buff[BUFFER_SIZE]; + while ((nread = fread(buff, 1, sizeof(buff), fp)) > 0) { + fwrite(buff, 1, nread, stdout); + } + + if (fclose(fp) != 0) { + perror("fclose"); + return EXIT_FAILURE; + } + } + + return EXIT_SUCCESS; +}