'simple' error message functions by Loic Grenie <loic.grenie@gmail.com>.
[oweals/busybox.git] / coreutils / touch.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini touch implementation for busybox
4  *
5  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
8  */
9
10 /* BB_AUDIT SUSv3 _NOT_ compliant -- options -a, -m, -r, -t not supported. */
11 /* http://www.opengroup.org/onlinepubs/007904975/utilities/touch.html */
12
13 /* Mar 16, 2003      Manuel Novoa III   (mjn3@codepoet.org)
14  *
15  * Previous version called open() and then utime().  While this will be
16  * be necessary to implement -r and -t, it currently only makes things bigger.
17  * Also, exiting on a failure was a bug.  All args should be processed.
18  */
19
20 #include "libbb.h"
21
22 /* This is a NOFORK applet. Be very careful! */
23
24 int touch_main(int argc, char **argv);
25 int touch_main(int argc, char **argv)
26 {
27         int fd;
28         int status = EXIT_SUCCESS;
29         int flags = getopt32(argv, "c");
30
31         argv += optind;
32
33         if (!*argv) {
34                 bb_show_usage();
35         }
36
37         do {
38                 if (utime(*argv, NULL)) {
39                         if (errno == ENOENT) {  /* no such file */
40                                 if (flags) {    /* Creation is disabled, so ignore. */
41                                         continue;
42                                 }
43                                 /* Try to create the file. */
44                                 fd = open(*argv, O_RDWR | O_CREAT,
45                                                   S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH
46                                                   );
47                                 if ((fd >= 0) && !close(fd)) {
48                                         continue;
49                                 }
50                         }
51                         status = EXIT_FAILURE;
52                         bb_simple_perror_msg(*argv);
53                 }
54         } while (*++argv);
55
56         return status;
57 }