• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* touch.c : change timestamp of a file
2  *
3  * Copyright 2012 Choubey Ji <warior.linux@gmail.com>
4  *
5  * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/touch.html
6  *
7  * -f is ignored for BSD/macOS compatibility. busybox/coreutils also support
8  * this, but only coreutils documents it in --help output.
9 
10 USE_TOUCH(NEWTOY(touch, "<1acd:fmr:t:h[!dtr]", TOYFLAG_BIN))
11 
12 config TOUCH
13   bool "touch"
14   default y
15   help
16     usage: touch FILE...
17 
18     Update the access and modification times of each FILE to the current time.
19 
20 */
21 
22 #define FOR_touch
23 #include "toys.h"
24 
25 GLOBALS(
26   char *t, *r, *d;
27 )
28 
touch_main(void)29 void touch_main(void)
30 {
31   struct timespec ts[2];
32   char **ss;
33   int fd, i;
34 
35   // use current time if no -t or -d
36   ts[0].tv_nsec = UTIME_NOW;
37 
38   if (FLAG(t) || FLAG(d)) {
39     time_t t = time(0);
40     unsigned nano;
41 
42     xparsedate(TT.t ? TT.t : TT.d, &t, &nano, 0);
43     ts->tv_sec = t;
44     ts->tv_nsec = nano;
45   }
46   ts[1]=ts[0];
47 
48   if (TT.r) {
49     struct stat st;
50 
51     xstat(TT.r, &st);
52     ts[0] = st.st_atim;
53     ts[1] = st.st_mtim;
54   }
55 
56   // Which time(s) should we actually change?
57   i = toys.optflags & (FLAG_a|FLAG_m);
58   if (i && i!=(FLAG_a|FLAG_m)) ts[i!=FLAG_m].tv_nsec = UTIME_OMIT;
59 
60   // Loop through files on command line
61   for (ss = toys.optargs; *ss;) {
62     char *s = *ss++;
63 
64     if (!strcmp(s, "-")) {
65       if (!futimens(1, ts)) continue;
66     } else {
67       // cheat: FLAG_h is rightmost flag, so its value is 1
68       if (!utimensat(AT_FDCWD, s, ts, FLAG(h)*AT_SYMLINK_NOFOLLOW)) continue;
69       if (FLAG(c)) continue;
70       if (access(s, F_OK) && (-1!=(fd = open(s, O_CREAT, 0666)))) {
71         close(fd);
72         if (toys.optflags) ss--;
73         continue;
74       }
75     }
76     perror_msg("'%s'", s);
77   }
78 }
79