Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write the code for implementation of cp that makes a copy of a file in C. The fi

ID: 3731173 • Letter: W

Question

Write the code for implementation of cp that makes a copy of a file in C. The file source name is supplied as an argument in the command line using the following syntax: cp src_file

As the result, the contents of src_file will be copied into a new file with the name X_copy_made_by_Y, where X is the name of src_file and Y is the name of cp executable. You are only allowed to use the system calls read(), write(), open(), creat() and close() to manipulate the files. Your code should check for reasonable errors and provide corresponding error messages.

Explanation / Answer

/*mycp.c*/

#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>


int main(int argc, char **argv){
    char    readbuf[80],readbuf1[80];
    int     fp1,fp2;
    int num_bytes;
    char name[30];
    char name2;

    if (argc != 2){
        return 0;
    }
    fp1 = open(argv[1],O_RDONLY);
   
    if (fp1 < 0){
       perror("Error opening file ");
       return 0;
    }
    strcpy(name,argv[1]);
    strcat(name,"_copy_made_by_");
   
    strcat(name,&argv[0][2]);
    //perror(name);
   
    fp2 = open(name,O_WRONLY);      
    if (fp2 < 0){
        perror("Error in creating file ");
        return 0;
    }
    num_bytes = read(fp1, readbuf, sizeof(readbuf));
    while (num_bytes > 0){
        write(fp2,readbuf,num_bytes);
        num_bytes = read(fp1, readbuf, sizeof(readbuf));
    }
   
    close(fp1);
    close(fp2);
   
    exit(0);
}