Arnaldo Carvalho de Melo | 4cf4013 | 2009-12-27 21:37:06 -0200 | [diff] [blame^] | 1 | #include <sys/mman.h> |
| 2 | #include <sys/stat.h> |
| 3 | #include <sys/types.h> |
| 4 | #include <fcntl.h> |
| 5 | #include <string.h> |
| 6 | #include <unistd.h> |
| 7 | #include "util.h" |
| 8 | |
| 9 | int mkdir_p(char *path, mode_t mode) |
| 10 | { |
| 11 | struct stat st; |
| 12 | int err; |
| 13 | char *d = path; |
| 14 | |
| 15 | if (*d != '/') |
| 16 | return -1; |
| 17 | |
| 18 | if (stat(path, &st) == 0) |
| 19 | return 0; |
| 20 | |
| 21 | while (*++d == '/'); |
| 22 | |
| 23 | while ((d = strchr(d, '/'))) { |
| 24 | *d = '\0'; |
| 25 | err = stat(path, &st) && mkdir(path, mode); |
| 26 | *d++ = '/'; |
| 27 | if (err) |
| 28 | return -1; |
| 29 | while (*d == '/') |
| 30 | ++d; |
| 31 | } |
| 32 | return (stat(path, &st) && mkdir(path, mode)) ? -1 : 0; |
| 33 | } |
| 34 | |
| 35 | int copyfile(const char *from, const char *to) |
| 36 | { |
| 37 | int fromfd, tofd; |
| 38 | struct stat st; |
| 39 | void *addr; |
| 40 | int err = -1; |
| 41 | |
| 42 | if (stat(from, &st)) |
| 43 | goto out; |
| 44 | |
| 45 | fromfd = open(from, O_RDONLY); |
| 46 | if (fromfd < 0) |
| 47 | goto out; |
| 48 | |
| 49 | tofd = creat(to, 0755); |
| 50 | if (tofd < 0) |
| 51 | goto out_close_from; |
| 52 | |
| 53 | addr = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fromfd, 0); |
| 54 | if (addr == MAP_FAILED) |
| 55 | goto out_close_to; |
| 56 | |
| 57 | if (write(tofd, addr, st.st_size) == st.st_size) |
| 58 | err = 0; |
| 59 | |
| 60 | munmap(addr, st.st_size); |
| 61 | out_close_to: |
| 62 | close(tofd); |
| 63 | if (err) |
| 64 | unlink(to); |
| 65 | out_close_from: |
| 66 | close(fromfd); |
| 67 | out: |
| 68 | return err; |
| 69 | } |