summaryrefslogtreecommitdiff
path: root/coreutils/cp.c
blob: 078a57c565b799ca8496f738a80c7b5df0f70295 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include "internal.h"
#include <stdio.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <sys/param.h>
#include <errno.h>

const char  cp_usage[] = "cp [-r] source-file destination-file\n"
"\t\tcp [-r] source-file [source-file ...] destination-directory\n"
"\n"
"\tCopy the source files to the destination.\n"
"\n"
"\t-r:\tRecursively copy all files and directories\n"
"\t\tunder the argument directory.";

extern int
cp_fn(const struct FileInfo * i)
{
    int         sourceFd;
    int         destinationFd;
    const char * destination = i->destination;
    struct stat destination_stat;
    int         status;
    char        buf[8192];
    char        d[PATH_MAX];

    if ( (i->stat.st_mode & S_IFMT) == S_IFDIR ) {
        if ( mkdir(destination, i->stat.st_mode & ~S_IFMT)
         != 0 && errno != EEXIST ) {
            name_and_error(destination);
            return 1;
        }
        return 0;
    }
    if ( (sourceFd = open(i->source, O_RDONLY)) < 0 ) {
        name_and_error(i->source);
        return 1;
    }
    if ( stat(destination, &destination_stat) == 0 ) {
        if ( i->stat.st_ino == destination_stat.st_ino
         &&  i->stat.st_dev == destination_stat.st_dev ) {
            fprintf(stderr
            ,"copy of %s to %s would copy file to itself.\n"
            ,i->source
            ,destination);
            close(sourceFd);
            return 1;
        }
    }
    /*
     * If the destination is a directory, create a file within it.
     */
    if ( (destination_stat.st_mode & S_IFMT) == S_IFDIR ) {
		destination = join_paths(
		 d
		,i->destination
		,&i->source[i->directoryLength]);

        if ( stat(destination, &destination_stat) == 0 ) {
            if ( i->stat.st_ino == destination_stat.st_ino
             &&  i->stat.st_dev == destination_stat.st_dev ) {
                fprintf(stderr
                ,"copy of %s to %s would copy file to itself.\n"
                ,i->source
                ,destination);
                close(sourceFd);
                return 1;
            }
        }
    }

    destinationFd = creat(destination, i->stat.st_mode & 07777);

    while ( (status = read(sourceFd, buf, sizeof(buf))) > 0 ) {
        if ( write(destinationFd, buf, status) != status ) {
            name_and_error(destination);
            close(sourceFd);
            close(destinationFd);
            return 1;
        }
    }
    close(sourceFd);
    close(destinationFd);
    if ( status < 0 ) {
        name_and_error(i->source);
        return 1;
    }
    return 0;
}