8 const char cp_usage[] = "cp [-r] source-file destination-file\n"
9 "\t\tcp [-r] source-file [source-file ...] destination-directory\n"
11 "\tCopy the source files to the destination.\n"
13 "\t-r:\tRecursively copy all files and directories\n"
14 "\t\tunder the argument directory.";
17 cp_fn(const struct FileInfo * i)
21 const char * destination = i->destination;
22 struct stat destination_stat;
27 if ( (i->stat.st_mode & S_IFMT) == S_IFDIR ) {
28 if ( mkdir(destination, i->stat.st_mode & ~S_IFMT)
29 != 0 && errno != EEXIST ) {
30 name_and_error(destination);
35 if ( (sourceFd = open(i->source, O_RDONLY)) < 0 ) {
36 name_and_error(i->source);
39 if ( stat(destination, &destination_stat) == 0 ) {
40 if ( i->stat.st_ino == destination_stat.st_ino
41 && i->stat.st_dev == destination_stat.st_dev ) {
43 ,"copy of %s to %s would copy file to itself.\n"
51 * If the destination is a directory, create a file within it.
53 if ( (destination_stat.st_mode & S_IFMT) == S_IFDIR ) {
54 destination = join_paths(
57 ,&i->source[i->directoryLength]);
59 if ( stat(destination, &destination_stat) == 0 ) {
60 if ( i->stat.st_ino == destination_stat.st_ino
61 && i->stat.st_dev == destination_stat.st_dev ) {
63 ,"copy of %s to %s would copy file to itself.\n"
72 destinationFd = creat(destination, i->stat.st_mode & 07777);
74 while ( (status = read(sourceFd, buf, sizeof(buf))) > 0 ) {
75 if ( write(destinationFd, buf, status) != status ) {
76 name_and_error(destination);
85 name_and_error(i->source);