touch.c 893 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include <u.h>
  2. #include <libc.h>
  3. int touch(int, char *);
  4. ulong now;
  5. void
  6. usage(void)
  7. {
  8. fprint(2, "usage: touch [-c] [-t time] files\n");
  9. exits("usage");
  10. }
  11. void
  12. main(int argc, char **argv)
  13. {
  14. int nocreate = 0;
  15. int status = 0;
  16. now = time(0);
  17. ARGBEGIN{
  18. case 't':
  19. now = strtoul(EARGF(usage()), 0, 0);
  20. break;
  21. case 'c':
  22. nocreate = 1;
  23. break;
  24. default:
  25. usage();
  26. }ARGEND
  27. if(!*argv)
  28. usage();
  29. while(*argv)
  30. status += touch(nocreate, *argv++);
  31. if(status)
  32. exits("touch");
  33. exits(0);
  34. }
  35. touch(int nocreate, char *name)
  36. {
  37. Dir stbuff;
  38. int fd;
  39. nulldir(&stbuff);
  40. stbuff.mtime = now;
  41. if(dirwstat(name, &stbuff) >= 0)
  42. return 0;
  43. if(nocreate){
  44. fprint(2, "touch: %s: cannot wstat: %r\n", name);
  45. return 1;
  46. }
  47. if ((fd = create(name, OREAD, 0666)) < 0) {
  48. fprint(2, "touch: %s: cannot create: %r\n", name);
  49. return 1;
  50. }
  51. dirfwstat(fd, &stbuff);
  52. close(fd);
  53. return 0;
  54. }