Task 1 (25 points)
The
following program copy.c is not efficient because it reads 1 byte at a time from
the source file and write 1 byte to the destination file. It also doesn’t have
any error checking code.
In this task, you will modify copy.c to
make it more efficient (i.e. read/write 1000 bytes at a time. Additionally, you
also need to add error checking code after open().
You can generate a random file to test your
program using the following command:
hb117@uxb4:~$ base64 /dev/urandom | head -c
41787 > foo
Your
program should work like this. (assuming nofoo doesn’t exist)
hb117@uxb4:~$ base64 /dev/urandom | head -c
41787 > foo
hb117@uxb4:~$ gcc -W copy.c -o copy
hb117@uxb4:~$ ./copy nofoo newfoo
Cannot open nofoo: No such file or directory
hb117@uxb4:~$ ./copy foo newfoo
hb117@uxb4:~$ ls -l
total 4
-rwx--x--x 1 hb117 faculty
8952 Nov 10 10:54 copy
-rw------- 1 hb117 faculty
680 Nov 10 10:54 copy.c
-rw------- 1 hb117 faculty
41787 Nov 10 10:53 foo
-rw------- 1 hb117 faculty 41787
Nov 10 11:24 newfoo
Here is copy.c:
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *source=argv[1];
char
*destination=argv[2];
int input =
open(source, O_RDONLY);
int output =
open(destination, O_WRONLY | O_CREAT, 0600);
char c;
while(1){
int r =
read(input, &c, 1);
if(r==0){
break;
}
write(output,
&c,1);
}
close(input);
close(output);
return 0;
}
Get Free Quote!
281 Experts Online