1 Introduction

In this workshop you will investigate file I/O and file copy operations.

2 Specification

Following on from the demonstration program cp1.c presented in the lecture, we will make a series of modifi- cations to the program.

Firstly, whathappenswhenthe cp1.c programisaskedtocopyafileontoitself, i.e. cp1 input input ? Is this what you expect? Modify the program to do something more sensible! As a hint, two files are the same if they are on the same device and have the same i-node number (which stat() can give you), simply comparing the names is not enough.

Secondly, a real copy program will assign the same file permissions to the destination as were on the source, modify your answer to the last part to do this.

Thirdly, real copy programs allow the second argument to be a directory, modify the answer to the last part to include this functionality. You should allocate the space for the new name dynamically.

3 Sample Code

3.1 cp1.c

#include < stdio.h>
#include < unistd.h>
#include < fcntl.h>
#define BUFFERSIZE 4096
#define COPYMODE 0644
void oops(char* , char * );

main(int ac, char* av[])
{
int in_fd, out_fd, n_chars;
char buf[BUFFERSIZE];
if ( ac != 3 ){
fprintf( stderr, "usage: %s source destinationn", * av);
exit(1);
}

if ( (in_fd=open(av[1], O_RDONLY)) == -1 )
oops("Cannot open ", av[1]);
if ( (out_fd=creat( av[2], COPYMODE)) == -1 )
oops( "Cannot creat", av[2]);
while ( (n_chars = read(in_fd , buf, BUFFERSIZE)) > 0 )
if ( write( out_fd, buf, n_chars ) != n_chars )
oops("Write error to ", av[2]);
if ( n_chars == -1 )
oops("Read error from ", av[1]);
if ( close(in_fd) == -1 || close(out_fd) == -1 )
oops("Error closing files","");
}

void oops(char* s1, char * s2)
{
fprintf(stderr,"Error: %s ", s1);
perror(s2);
exit(1);
}
Academic Honesty!
It is not our intention to break the school's academic policy. Posted solutions are meant to be used as a reference and should not be submitted as is. We are not held liable for any misuse of the solutions. Please see the frequently asked questions page for further questions and inquiries.
Kindly complete the form. Please provide a valid email address and we will get back to you within 24 hours. Payment is through PayPal, Buy me a Coffee or Cryptocurrency. We are a nonprofit organization however we need funds to keep this organization operating and to be able to complete our research and development projects.