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

73 lines
1.5 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 8
int main() {
extern int errno;
char file_read[] = "f_read.txt";
char file_write[] = "f_write.txt";
char buffer[BUFFSIZE];
bzero(buffer, sizeof(buffer));
// opening files
int desc_fr = open(file_read, O_RDONLY);
if (desc_fr < 0) {
perror("ERROR opening f_read.txt");
exit(errno);
}
int desc_fw = open(file_write, O_WRONLY | O_CREAT | O_TRUNC, 0640);
if (desc_fw < 0) {
perror("ERROR opening f_write.txt");
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) {
perror("ERROR reading f_read.txt");
exit(errno);
}
printf("[%d] %.*s\n", ret_read, ret_read, buffer);
ret_write = write(desc_fw, buffer, ret_read);
if (ret_write < 0) {
perror("ERROR writing to f_write.txt");
exit(errno);
}
bzero(buffer, sizeof(buffer));
}
// closing files
int ret_close = 0;
ret_close = close(desc_fr);
if (ret_close < 0) {
perror("ERROR closing f_read.txt");
exit(errno);
}
close(desc_fw);
if (ret_close < 0) {
perror("ERROR closing f_write.txt");
exit(errno);
}
return EXIT_SUCCESS;
}