I have written the code for implementation of the cp program that prints the number of bytes copied when the user presses Ctrl-C. Could someone please review this code and provide feedback. Thanks a lot.
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<error.h>
#include<signal.h>
#define buffer_size 512
void signal_handler(int num);
void write_buf(int des_fd, char *buffer, size_t rlen, int *bytes);
int flag = 0;
void signal_handler(int num)
{
printf("The caught signal number is : %d\n", num);
flag = 1;
}
void write_buf(int des_fd, char *buffer, size_t rlen, int *bytes)
{
int wlen;
while (1) {
wlen = write(des_fd, buffer, rlen);
if (wlen == -1)
error(1, 0, "error in writing the file\n");
*bytes = *bytes + wlen;
buffer = buffer + wlen;
rlen = rlen - wlen;
if (rlen == 0)
break;
}
}
int main()
{
int src_fd;
int des_fd;
int rlen;
int bytes;
char buffer[buffer_size];
signal(SIGINT, signal_handler);
src_fd = open("src_text", O_RDONLY);
if (src_fd == -1)
error(1, 0, "error in opening the source-file\n");
des_fd = open("des_txt", O_WRONLY);
while (1) {
rlen = read(src_fd, buffer, sizeof(buffer));
if (rlen == -1)
error(1, 0, "error in reading the file\n");
if (rlen == 0)
break;
write_buf(des_fd, buffer, rlen, &bytes);
if (flag == 1)
printf("The number of bytes copied is :%d\n", bytes);
flag = 0;
}
}
```