File: touch.c

package info (click to toggle)
libite 2.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,188 kB
  • sloc: sh: 4,665; ansic: 4,165; makefile: 141
file content (92 lines) | stat: -rw-r--r-- 1,806 bytes parent folder | download
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* test of touch(), touchf(), erase(), and erasef() */
#include <err.h>
#include <paths.h>
#include <signal.h>
#include <stdarg.h>
#include <time.h>

#include "check.h"

#define FMT "%s-bar"

int verbose = 0;


static int mtime(char *file)
{
	int ret;
	char buf[80];
	struct stat before, after;

	PRINT("Calling touch() to create file ...\n");
	touch(file);
	stat(file, &before);

	/* Must sleep a while here otherwise we execute too fast => no mtime change :-( */
	sleep(2);

	PRINT("Calling touch() again to update mtime ...\n");
	if (touch(file)) {
		erase(file);
		err(1, "Failed creating %s", file);
	}
	stat(file, &after);

	ret = timespec_newer(&after.st_mtim, &before.st_mtim);
	PRINT("Before: %s\n", timespec2str(&before.st_mtim, buf, sizeof(buf)));
	PRINT("After : %s\n", timespec2str(&after.st_mtim, buf, sizeof(buf)));
	erase(file);

	return !ret;
}

static int formatted(char *file)
{
	char vrfy[80];

	if (touchf(FMT, file))
		err(1, "Failed creating " FMT, file);

	PRINT("Created " FMT "\n", file);

	snprintf(vrfy, sizeof(vrfy), FMT, file);
	if (!fexist(vrfy))
		errx(1, "touchf() does not detect failure to create file " FMT, file);

	PRINT("File " FMT " really does exist!\n", file);

	erasef(FMT, file);
	if (fexist(vrfy)) {
		int saved = errno;

		erase(vrfy);
		errno = saved;
		errx(1, "erasef() failed removing the created file " FMT, file);
	}

	return 0;
}

int main(int argc, char *argv[])
{
	int fd;
	char file[42] = "/tmp/touch_test.XXXXXX";

	if (argc > 1 && !strcmp(argv[1], "-v"))
		verbose = 1;

	fd = mkstemp(file);
	if (fd < 0)
		err(1, "Failed creating tempfile, %s", file);
	close(fd);

	return mtime(file) || formatted(file);
}

/**
 * Local Variables:
 *  indent-tabs-mode: t
 *  c-file-style:     "linux"
 *  compile-command:  "make touch && ./touch -v"
 * End:
 */