// mycopy.c /* mycopy utility * makes a copy of a file and assigns the same file
ID: 3703428 • Letter: #
Question
// mycopy.c
/* mycopy utility
* makes a copy of a file and assigns the same file
* permissions to the copy
* Usage:
* ./mycopy <name of original file> <name of copy>
* If the original file does not exist or the user
* lacks permission to read it, mycopy emits an error.
* Also, if a file or directory exists with the name
* proposed for the copy, mycopy emits an error and
* terminates.
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int error( char * msg )
{
perror( msg );
return 2;
}
int usage( char * name )
{
printf( "Usage: %s <file to copy> <name of copy> ", name );
return 1;
}
int main( int argc, char * argv[] )
{
if ( argc != 3 )
return usage( argv[0] );
// open files
// read bytes from original file and
// write to copy
// close files
return 0;
}
imple file utilities using theC You are to create two s the contents of text files language-- one to copy files and the other to display 1. mycopy This is the simpler of the two utilities; it simply copies a file. Following are the specifications: 1. The usage of mycopy is as follows: mycopy 2. If the file to be copied does not exist or the user lacks permission to read it, mycopy emits 3. If a file or directory already exists with the name proposed for the copy, mycopy emits an 4. You are to write code within the main function of the file mycopy.c, which is supplied an error message and quits error and terminates with this assignment. You may also add your own functions, if you wish ? mtrnageExplanation / Answer
#include<studio.h>
int error( char *msg){
perror (char *msg); // displays error messages accordingly
return (1);
}
int usage(char *name){
printf("Usage : %s <file to copy> <name of copy> ", name);
return 1;
}
int main(int argc, char *argc[]){
FILE *source, *copy;
if(argc != 3)
return usage(argc[0]); // run the program with corrrec input
source=fopen(argv[1], "r"); //opens source file in read mode
if(source==NULL)
error("fopen() error"); //file couldn't open or no read privilege
copy=fopen(argv[2], "r"); // opens file to copy
if(copy){ // if file already exists
fclose(copy); // close the file
error("Filename already exists"); // displays error message
}
copy=fopen(argv[2], "w"); //open copy file in write mode
while((ch=fgetc(source))!=EOF)
fputc(ch, copy); // copy contents of source to copy until eof
printf("File copied successfully");
fclose(source);
fclose(copy);
if(copy = fopen(argv[2],"r"))
while((ch=fgetc(copy))!=EOF)
putc(ch); // displays contebts of file copy
fclose(copy);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.