-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcp.c
More file actions
68 lines (56 loc) · 1.51 KB
/
cp.c
File metadata and controls
68 lines (56 loc) · 1.51 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: cp src dest\n");
return 1;
}
char *src = argv[1];
char *dst = argv[2];
struct stat st_src, st_dst;
/* stat src */
if (stat(src, &st_src) == -1) {
perror(src);
return 1;
}
/* Проверка копирования в самого себя */
if (stat(dst, &st_dst) == 0) {
if (st_src.st_dev == st_dst.st_dev &&
st_src.st_ino == st_dst.st_ino) {
fprintf(stderr, "cp: '%s' and '%s' are the same file\n", src, dst);
return 1;
}
}
int fd_src = open(src, O_RDONLY);
if (fd_src == -1) {
perror(src);
return 1;
}
int fd_dst = open(dst,
O_WRONLY | O_CREAT | O_TRUNC,
st_src.st_mode & 07777); /* копируем права */
if (fd_dst == -1) {
perror(dst);
close(fd_src);
return 1;
}
char buffer[4096];
ssize_t n;
while ((n = read(fd_src, buffer, sizeof(buffer))) > 0) {
if (write(fd_dst, buffer, n) != n) {
perror("write");
close(fd_src);
close(fd_dst);
return 1;
}
}
if (n < 0)
perror("read");
close(fd_src);
close(fd_dst);
return 0;
}