touch.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. USE_TOUCH(NEWTOY(touch, "<1acd:fmr:t:h[!dtr]", TOYFLAG_BIN))
  10. config TOUCH
  11. bool "touch"
  12. default y
  13. help
  14. usage: touch [-amch] [-d DATE] [-t TIME] [-r FILE] FILE...
  15. Update the access and modification times of each FILE to the current time.
  16. -a Change access time
  17. -m Change modification time
  18. -c Don't create file
  19. -h Change symlink
  20. -d Set time to DATE (in YYYY-MM-DDThh:mm:SS[.frac][tz] format)
  21. -t Set time to TIME (in [[CC]YY]MMDDhhmm[.ss][frac] format)
  22. -r Set time same as reference FILE
  23. */
  24. #define FOR_touch
  25. #include "toys.h"
  26. GLOBALS(
  27. char *t, *r, *d;
  28. )
  29. void touch_main(void)
  30. {
  31. struct timespec ts[2];
  32. char **ss;
  33. int fd, i;
  34. // use current time if no -t or -d
  35. ts[0].tv_nsec = UTIME_NOW;
  36. if (FLAG(t) || FLAG(d)) {
  37. time_t t = time(0);
  38. unsigned nano;
  39. xparsedate(TT.t ? TT.t : TT.d, &t, &nano, 0);
  40. ts->tv_sec = t;
  41. ts->tv_nsec = nano;
  42. }
  43. ts[1]=ts[0];
  44. if (TT.r) {
  45. struct stat st;
  46. xstat(TT.r, &st);
  47. ts[0] = st.st_atim;
  48. ts[1] = st.st_mtim;
  49. }
  50. // Which time(s) should we actually change?
  51. i = toys.optflags & (FLAG_a|FLAG_m);
  52. if (i && i!=(FLAG_a|FLAG_m)) ts[i!=FLAG_m].tv_nsec = UTIME_OMIT;
  53. // Loop through files on command line
  54. for (ss = toys.optargs; *ss;) {
  55. char *s = *ss++;
  56. if (!strcmp(s, "-")) {
  57. if (!futimens(1, ts)) continue;
  58. } else {
  59. // cheat: FLAG_h is rightmost flag, so its value is 1
  60. if (!utimensat(AT_FDCWD, s, ts, FLAG(h)*AT_SYMLINK_NOFOLLOW)) continue;
  61. if (FLAG(c)) continue;
  62. if (access(s, F_OK) && (-1!=(fd = open(s, O_CREAT, 0666)))) {
  63. close(fd);
  64. if (toys.optflags) ss--;
  65. continue;
  66. }
  67. }
  68. perror_msg("'%s'", s);
  69. }
  70. }