morpheus-base

morpheus base system
git clone git://git.2f30.org/morpheus-base
Log | Files | Refs

touch.c (1208B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <errno.h>
      3 #include <fcntl.h>
      4 #include <stdlib.h>
      5 #include <sys/stat.h>
      6 #include <time.h>
      7 #include <unistd.h>
      8 #include <utime.h>
      9 
     10 #include "util.h"
     11 
     12 static int aflag;
     13 static int cflag;
     14 static int mflag;
     15 static time_t t;
     16 
     17 static void
     18 touch(const char *file)
     19 {
     20 	int fd;
     21 	struct stat st;
     22 	struct utimbuf ut;
     23 	int r;
     24 
     25 	if ((r = stat(file, &st)) < 0) {
     26 		if (errno != ENOENT)
     27 			eprintf("stat %s:", file);
     28 		if (cflag)
     29 			return;
     30 	} else if (r == 0) {
     31 		ut.actime = aflag ? t : st.st_atime;
     32 		ut.modtime = mflag ? t : st.st_mtime;
     33 		if (utime(file, &ut) < 0)
     34 			eprintf("utime %s:", file);
     35 		return;
     36 	}
     37 
     38 	if ((fd = open(file, O_CREAT | O_EXCL, 0644)) < 0)
     39 		eprintf("open %s:", file);
     40 	close(fd);
     41 
     42 	touch(file);
     43 }
     44 
     45 static void
     46 usage(void)
     47 {
     48 	eprintf("usage: %s [-acm] [-t stamp] file ...\n", argv0);
     49 }
     50 
     51 int
     52 main(int argc, char *argv[])
     53 {
     54 	t = time(NULL);
     55 
     56 	ARGBEGIN {
     57 	case 'a':
     58 		aflag = 1;
     59 		break;
     60 	case 'c':
     61 		cflag = 1;
     62 		break;
     63 	case 'm':
     64 		mflag = 1;
     65 		break;
     66 	case 't':
     67 		t = estrtol(EARGF(usage()), 0);
     68 		break;
     69 	default:
     70 		usage();
     71 	} ARGEND;
     72 
     73 	if (argc < 1)
     74 		usage();
     75 
     76 	for (; argc > 0; argc--, argv++)
     77 		touch(argv[0]);
     78 
     79 	return 0;
     80 }