Write a simple UNIX cp clone

This commit is contained in:
Fabio Scotto di Santolo
2025-09-17 18:33:08 +02:00
parent ef8d74ec19
commit a611ca2fc3
3 changed files with 282 additions and 0 deletions

View File

@@ -0,0 +1,19 @@
CC := gcc
CFLAGS := -Wall -Wextra -pedantic -std=c11 -pthread -g
TARGET := cp
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)

View File

@@ -0,0 +1,59 @@
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 4096
int main(int argc, char *argv[])
{
if (argc < 3) {
fprintf(stderr, "Usage: %s SRC DEST", argv[0]);
return EXIT_FAILURE;
}
const char *src = argv[1];
const char *dest = argv[2];
FILE *fp1 = fopen(src, "rb");
if (fp1 == NULL) {
perror("cannot open source file");
return EXIT_FAILURE;
}
FILE *fp2 = fopen(dest, "wb");
if (fp2 == NULL) {
perror("cannot open destination file");
fclose(fp1);
return EXIT_FAILURE;
}
size_t nread;
unsigned char buff[BUFFER_SIZE];
while ((nread = fread(buff, 1, sizeof(buff), fp1)) > 0) {
if (fwrite(buff, 1, nread, fp2) != nread) {
perror("fwrite");
fclose(fp1);
fclose(fp2);
return EXIT_FAILURE;
}
}
if (ferror(fp1)) {
perror("read error");
fclose(fp1);
fclose(fp2);
return EXIT_FAILURE;
}
if (fclose(fp1) != 0) {
perror("cannot close source file");
return EXIT_FAILURE;
}
if (fclose(fp2) != 0) {
perror("cannot close destination file");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}

View File

@@ -0,0 +1,204 @@
This a simple file for testing my clone cp program
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test
This a test