90fb31e93e97929f523e03f0c06e289d824bad2c
[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
15 int
16 main(int argc, char** argv)
17 {
18   int rc;
19   int i=0;
20   int fd;
21   int wBitSet = 0;
22   struct _stat sb;
23
24   if (argc == 1) {
25     fprintf(stderr, "Usage: %s <files>\n", argv[0]);
26     return 1;
27   }
28   
29   
30   while (i++ < (argc-1)) {
31     if ( (_access(argv[i], 00) < 0) && (errno == ENOENT || errno == EACCES) ) {
32        /* File doesn't exist, try creating it. */
33       if ( (fd = _open(argv[i], _O_CREAT | _O_EXCL | _O_TRUNC, _S_IREAD | _S_IWRITE)) < 0 ) {
34         fprintf(stderr, "Unable to create %s, skipping.\n", argv[i]);
35       } else {
36         _close(fd);
37       }
38     }
39     if ( (_access(argv[i], 02)) < 0 ) {
40         /* No write permission, try setting it first. */
41         if (_stat(argv[i], &sb) < 0) {
42            fprintf(stderr, "Unable to change mod. time for %s  (%d)\n", argv[i], errno);
43            continue;
44         }
45         if (_chmod(argv[i], (sb.st_mode & _S_IREAD) | _S_IWRITE) < 0) {
46            fprintf(stderr, "Unable to change mod. time for %s  (%d)\n", argv[i], errno);
47            continue;
48         }
49         wBitSet = 1;
50     }
51     if ( (rc = _utime(argv[i],NULL)) < 0) {
52       fprintf(stderr, "Unable to change mod. time for %s  (%d)\n", argv[i], errno);
53     }
54     if (wBitSet) {
55         /* Turn the file back into a read-only file */
56         _chmod(argv[i], (sb.st_mode & _S_IREAD));
57         wBitSet = 0;
58     }
59   }
60   
61   return 0;
62 }
63 #endif