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

Write the complete code for your implementation of cp that makes a copy of a fil

ID: 3735990 • Letter: W

Question

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

As a result, the contents of src_file will be copied into a new file with the name XXX_copy_made_by_YYY, where XXX is the name of src_file and YYY is the name of cp executable. You are only allowed to user read (), write (), open (), creat () and close () to manipulate the files. Your code should check for reasonable errors and provide corresponding error messages. Make every attempt to properly indent and comment your code.

Explanation / Answer

Please find my code:

/*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);
}