TP-systeme-exploitation-cen.../TP3/verif_fichiers/etu/copier.c
2023-06-20 20:57:09 +02:00

75 lines
1.8 KiB
C

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#define BUFFSIZE 4096
int main(int argc, char* argv[]) {
extern int errno;
char* file_read = argv[1];
char* file_write = argv[2];
char buffer[BUFFSIZE];
bzero(buffer, sizeof(buffer));
// opening files
int desc_fr = open(file_read, O_RDONLY);
if (desc_fr < 0) {
fprintf(stderr, "ERROR: opening %s : %s\n", file_read, strerror(errno));
exit(errno);
}
int desc_fw = open(file_write, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (desc_fw < 0) {
fprintf(stderr, "ERROR: opening %s : %s\n", file_write, strerror(errno));
exit(errno);
}
// reading and writing to buffer
int ret_write = 0;
int ret_read = BUFFSIZE;
while (ret_read == BUFFSIZE) {
ret_read = read(desc_fr, buffer, BUFFSIZE);
if (ret_read < 0) {
fprintf(stderr, "ERROR: reading %s : %s\n", file_read, strerror(errno));
exit(errno);
}
printf("[%d] %.*s\n", ret_read, ret_read, buffer); // debug
ret_write = write(desc_fw, buffer, ret_read);
if (ret_write < 0) {
fprintf(stderr, "ERROR: writing to %s : %s\n", file_write, strerror(errno));
exit(errno);
}
bzero(buffer, sizeof(buffer));
}
// closing files
int ret_close = 0;
ret_close = close(desc_fr);
if (ret_close < 0) {
fprintf(stderr, "ERROR: closing %s : %s\n", file_read, strerror(errno));
exit(errno);
}
close(desc_fw);
if (ret_close < 0) {
fprintf(stderr, "ERROR: closing %s : %s\n", file_write, strerror(errno));
exit(errno);
}
return EXIT_SUCCESS;
}
// perror