/
touch.c
62 lines (56 loc) · 1.08 KB
/
touch.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/* 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[])
{
char c;
t = time(NULL);
while((c = getopt(argc, argv, "ct:")) != -1)
switch(c) {
case 'c':
cflag = true;
break;
case 't':
t = estrtol(optarg, 0);
break;
default:
exit(EXIT_FAILURE);
}
for(; optind < argc; optind++)
touch(argv[optind]);
return EXIT_SUCCESS;
}
void
touch(const char *str)
{
int fd;
struct stat st;
struct utimbuf ut;
if(stat(str, &st) == 0) {
ut.actime = st.st_atime;
ut.modtime = t;
if(utime(str, &ut) == -1)
eprintf("utime %s:", str);
return;
}
else if(errno != ENOENT)
eprintf("stat %s:", str);
else if(cflag)
return;
if((fd = open(str, O_CREAT|O_EXCL,
S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)) == -1)
eprintf("open %s:", str);
close(fd);
touch(str);
}