touch.c 960 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. char *t, *s;
  15. int nocreate = 0;
  16. int status = 0;
  17. now = time(0);
  18. ARGBEGIN{
  19. case 't':
  20. t = EARGF(usage());
  21. now = strtoul(t, &s, 0);
  22. if(s == t || *s != '\0')
  23. usage();
  24. break;
  25. case 'c':
  26. nocreate = 1;
  27. break;
  28. default:
  29. usage();
  30. }ARGEND
  31. if(!*argv)
  32. usage();
  33. while(*argv)
  34. status += touch(nocreate, *argv++);
  35. if(status)
  36. exits("touch");
  37. exits(0);
  38. }
  39. touch(int nocreate, char *name)
  40. {
  41. Dir stbuff;
  42. int fd;
  43. nulldir(&stbuff);
  44. stbuff.mtime = now;
  45. if(dirwstat(name, &stbuff) >= 0)
  46. return 0;
  47. if(nocreate){
  48. fprint(2, "touch: %s: cannot wstat: %r\n", name);
  49. return 1;
  50. }
  51. if((fd = create(name, OREAD|OEXCL, 0666)) < 0){
  52. fprint(2, "touch: %s: cannot create: %r\n", name);
  53. return 1;
  54. }
  55. dirfwstat(fd, &stbuff);
  56. close(fd);
  57. return 0;
  58. }