sbase/touch.c

62 lines
1.1 KiB
C
Raw Normal View History

2011-05-23 01:36:34 +00:00
/* See LICENSE file for copyright and license details. */
#include <errno.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <utime.h>
#include <sys/stat.h>
#include "util.h"
static void touch(const char *);
static bool cflag = false;
static time_t t;
int
main(int argc, char *argv[])
{
2011-05-25 10:42:17 +00:00
char *end, c;
2011-05-23 01:36:34 +00:00
t = time(NULL);
2011-05-24 00:13:34 +00:00
while((c = getopt(argc, argv, "ct:")) != -1)
switch(c) {
case 'c':
2011-05-23 01:36:34 +00:00
cflag = true;
break;
2011-05-24 00:13:34 +00:00
case 't':
2011-05-25 10:42:17 +00:00
t = strtol(optarg, &end, 0);
if(*end != '\0')
eprintf("%s: not a number\n", optarg);
2011-05-24 00:13:34 +00:00
break;
default:
exit(EXIT_FAILURE);
}
for(; optind < argc; optind++)
touch(argv[optind]);
2011-05-23 01:36:34 +00:00
return EXIT_SUCCESS;
}
void
touch(const char *str)
{
int fd;
struct stat st;
struct utimbuf ut;
2011-06-04 11:20:41 +00:00
if(stat(str, &st) == -1) {
2011-05-23 01:36:34 +00:00
if(errno != ENOENT)
eprintf("stat %s:", str);
if(cflag)
return;
2011-05-28 14:37:42 +00:00
if((fd = creat(str, O_EXCL|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)) < 0)
2011-05-23 01:36:34 +00:00
eprintf("creat %s:", str);
close(fd);
}
ut.actime = st.st_atime;
ut.modtime = t;
2011-06-04 11:20:41 +00:00
if(utime(str, &ut) == -1)
2011-05-23 01:36:34 +00:00
eprintf("utime %s:", str);
}