GHC new build system megapatch
[ghc-hetmet.git] / utils / touchy / touchy.c
1 /*
2  * Simple _utime() wrapper for setting the mod. time on files
3  * to the current system time.
4  *
5  */
6 #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(_WIN32)
7 #error "Win32-only, the platform you're using is supposed to have 'touch' already."
8 #else
9 #include <stdio.h>
10 #include <sys/stat.h>
11 #include <sys/types.h>
12 #include <fcntl.h>
13 #include <errno.h>
14 #include <utime.h>
15
16 int
17 main(int argc, char** argv)
18 {
19   int rc;
20   int i=0;
21   int fd;
22   int wBitSet = 0;
23   struct _stat sb;
24
25   if (argc == 1) {
26     fprintf(stderr, "Usage: %s <files>\n", argv[0]);
27     return 1;
28   }
29   
30   
31   while (i++ < (argc-1)) {
32     if ( (_access(argv[i], 00) < 0) && (errno == ENOENT || errno == EACCES) ) {
33        /* File doesn't exist, try creating it. */
34       if ( (fd = _open(argv[i], _O_CREAT | _O_EXCL | _O_TRUNC, _S_IREAD | _S_IWRITE)) < 0 ) {
35         fprintf(stderr, "Unable to create %s, skipping.\n", argv[i]);
36       } else {
37         _close(fd);
38       }
39     }
40     if ( (_access(argv[i], 02)) < 0 ) {
41         /* No write permission, try setting it first. */
42         if (_stat(argv[i], &sb) < 0) {
43            fprintf(stderr, "Unable to change mod. time for %s  (%d)\n", argv[i], errno);
44            continue;
45         }
46         if (_chmod(argv[i], (sb.st_mode & _S_IREAD) | _S_IWRITE) < 0) {
47            fprintf(stderr, "Unable to change mod. time for %s  (%d)\n", argv[i], errno);
48            continue;
49         }
50         wBitSet = 1;
51     }
52     if ( (rc = _utime(argv[i],NULL)) < 0) {
53       fprintf(stderr, "Unable to change mod. time for %s  (%d)\n", argv[i], errno);
54     }
55     if (wBitSet) {
56         /* Turn the file back into a read-only file */
57         _chmod(argv[i], (sb.st_mode & _S_IREAD));
58         wBitSet = 0;
59     }
60   }
61   
62   return 0;
63 }
64 #endif