Exercise: Copy A File#
Requirement#
Write a program cp-for-the-poor which exhibits the following
behavior:
It interprets its two arguments as filenames, and copies the first to the second
The first filename must be an existing file
The second filename is the target of the copy
No existing file must be overwritten
The program operates at the system call layer. Use
open()/read()/write()/close(), and not anything from<stdio.h>.
Note
Check for system call errors; see errno, And Error Handling for how to.
Make sure the program interprets its commandline correctly; see Argument Vector (argv) for how to.
Make sure the program returns exit statuses as specified below; see Process Termination: Exit Status for how to.
Sunny Case: Source File Exists, Destination Does Not Exist#
$ ./cp-for-the-poor /etc/passwd /tmp/passwd-copy
$ echo $?
0
Error: Wrong Number Of Arguments Specified#
$ ./cp-for-the-poor
./cp-for-the-poor: SRCFILE DSTFILE
$ echo $?
1
Error: Source File Does Not Exist#
$ ./cp-for-the-poor /etc/passwd-not-there /tmp/some-file-that-does-not-exist
/etc/passwd-not-there: No such file or directory
$ echo $?
2
Error: Destination File Exists#
Provided that /tmp/passwd-copy already exists [1]:
$ ./cp-for-the-poor /etc/passwd /tmp/passwd-copy
/tmp/passwd-copy: File exists
$ echo $?
3
Error: Destination Directory Not Writable#
Provided that /etc is not writable (because you are not root,
for example),
$ ./cp-for-the-poor /etc/passwd /etc/passwd-copy
/etc/passwd-copy: Permission denied
$ echo $?
4
Footnotes