[Toybox] [PATCH 2/2] Add a "touch" command.
Avery Pennarun
apenwarr at gmail.com
Wed Aug 15 20:56:06 PDT 2012
Doesn't implement optional manual setting of timestamp; just uses the
current time, which is the most common use case.
---
toys.h | 1 +
toys/touch.c | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 58 insertions(+), 0 deletions(-)
create mode 100644 toys/touch.c
diff --git a/toys.h b/toys.h
index 4a84bf4..2cc58af 100644
--- a/toys.h
+++ b/toys.h
@@ -37,6 +37,7 @@
#include <sys/statvfs.h>
#include <sys/sysinfo.h>
#include <sys/swap.h>
+#include <sys/time.h>
#include <sys/times.h>
#include <sys/types.h>
#include <sys/utsname.h>
diff --git a/toys/touch.c b/toys/touch.c
new file mode 100644
index 0000000..4bbfacd
--- /dev/null
+++ b/toys/touch.c
@@ -0,0 +1,57 @@
+/* vi: set sw=4 ts=4:
+ *
+ * touch.c - Create files and update their atime/mtime.
+ *
+ * Copyright 2012 Avery Pennarun <apenwarr at gmail.com>
+ *
+ * See http://www.opengroup.org/onlinepubs/009695399/utilities/touch.html
+ *
+USE_CP(NEWTOY(touch, "<1", TOYFLAG_BIN))
+
+config TOUCH
+ bool "touch"
+ default n
+ help
+ usage: touch <filenames...>
+
+ Updates the timestamps on the given files, and creates them if
+ they do not exist.
+*/
+
+#include "toys.h"
+
+#define TT this.touch
+
+
+void touch_file(char *filename, struct timeval *times)
+{
+ int fd = -1;
+
+ if (utimes(filename, times) < 0) {
+ if (errno != ENOENT) {
+ perror_exit("utimes(%s)", filename);
+ } else {
+ fd = open(filename, O_WRONLY|O_CREAT, 0666);
+ if (fd < 0) {
+ perror_exit("open '%s'", filename);
+ }
+ xclose(fd);
+ }
+ }
+}
+
+
+void touch_main(void)
+{
+ struct timeval times[2];
+ struct timezone tz;
+ int i;
+
+ gettimeofday(×[0], &tz);
+ times[1] = times[0];
+
+ for (i=0; i<toys.optc; i++) {
+ char *filename = toys.optargs[i];
+ touch_file(filename, times);
+ }
+}
--
1.7.9.dirty
More information about the Toybox
mailing list