Ken Sumrall | 795165b | 2011-04-05 20:46:30 -0700 | [diff] [blame] | 1 | #include <stdio.h> |
| 2 | #include <string.h> |
| 3 | #include <sys/types.h> |
| 4 | #include <fcntl.h> |
| 5 | #include <sys/stat.h> |
| 6 | #include <stdlib.h> |
| 7 | #include <fcntl.h> |
| 8 | |
| 9 | static void usage(void) |
| 10 | { |
| 11 | fprintf(stderr, "touch: usage: touch [-alm] [-t time_t] <file>\n"); |
| 12 | exit(1); |
| 13 | } |
| 14 | |
| 15 | int touch_main(int argc, char *argv[]) |
| 16 | { |
| 17 | int i, fd, aflag = 0, mflag = 0, debug = 0, flags = 0; |
| 18 | struct timespec specified_time, times[2]; |
| 19 | char *file = 0; |
| 20 | |
| 21 | specified_time.tv_nsec = UTIME_NOW; |
| 22 | |
| 23 | for (i = 1; i < argc; i++) { |
| 24 | if (argv[i][0] == '-') { |
| 25 | /* an option */ |
| 26 | const char *arg = argv[i]+1; |
| 27 | while (arg[0]) { |
| 28 | switch (arg[0]) { |
| 29 | case 'a': aflag = 1; break; |
| 30 | case 'm': mflag = 1; break; |
| 31 | case 't': |
| 32 | if ((i+1) >= argc) |
| 33 | usage(); |
| 34 | specified_time.tv_sec = atol(argv[++i]); |
| 35 | if (specified_time.tv_sec == 0) { |
| 36 | fprintf(stderr, "touch: invalid time_t\n"); |
| 37 | exit(1); |
| 38 | } |
| 39 | specified_time.tv_nsec = 0; |
| 40 | break; |
| 41 | case 'l': flags |= AT_SYMLINK_NOFOLLOW; break; |
| 42 | case 'd': debug = 1; break; |
| 43 | default: |
| 44 | usage(); |
| 45 | } |
| 46 | arg++; |
| 47 | } |
| 48 | } else { |
| 49 | /* not an option, and only accept one filename */ |
| 50 | if (i+1 != argc) |
| 51 | usage(); |
| 52 | file = argv[i]; |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | if (! file) { |
| 57 | fprintf(stderr, "touch: no file specified\n"); |
| 58 | exit(1); |
| 59 | } |
| 60 | |
| 61 | if (access(file, F_OK)) |
| 62 | if ((fd=creat(file, 0666)) != -1) |
| 63 | close(fd); |
| 64 | |
| 65 | if ((mflag == 0) && (aflag == 0)) |
| 66 | aflag = mflag = 1; |
| 67 | |
| 68 | if (aflag) |
| 69 | times[0] = specified_time; |
| 70 | else |
| 71 | times[0].tv_nsec = UTIME_OMIT; |
| 72 | |
| 73 | if (mflag) |
| 74 | times[1] = specified_time; |
| 75 | else |
| 76 | times[1].tv_nsec = UTIME_OMIT; |
| 77 | |
| 78 | if (debug) { |
| 79 | fprintf(stderr, "file = %s\n", file); |
| 80 | fprintf(stderr, "times[0].tv_sec = %ld, times[0].tv_nsec = %ld\n", times[0].tv_sec, times[0].tv_nsec); |
| 81 | fprintf(stderr, "times[1].tv_sec = %ld, times[1].tv_nsec = %ld\n", times[1].tv_sec, times[1].tv_nsec); |
| 82 | fprintf(stderr, "flags = 0x%8.8x\n", flags); |
| 83 | } |
| 84 | |
| 85 | return utimensat(AT_FDCWD, file, times, flags); |
| 86 | } |
| 87 | |