(utime_null): Don't pass 0666 to open; it's not needed and isn't
[gnulib.git] / lib / utime.c
1 /* Copyright (C) 1998 Free Software Foundation, Inc.
2
3    This program is free software; you can redistribute it and/or modify it
4    under the terms of the GNU General Public License as published by the
5    Free Software Foundation; either version 2, or (at your option) any
6    later version.
7
8    This program is distributed in the hope that it will be useful,
9    but WITHOUT ANY WARRANTY; without even the implied warranty of
10    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11    GNU General Public License for more details.
12
13    You should have received a copy of the GNU General Public License
14    along with this program; if not, write to the Free Software Foundation,
15    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
16
17 /* derived from a function in touch.c */
18
19 #ifdef HAVE_CONFIG_H
20 # include <config.h>
21 #endif
22 #undef utime
23
24 #include <sys/types.h>
25
26 #ifdef HAVE_UTIME_H
27 # include <utime.h>
28 #endif
29
30 #include "safe-read.h"
31
32 /* Some systems (even some that do have <utime.h>) don't declare this
33    structure anywhere.  */
34 #ifndef HAVE_STRUCT_UTIMBUF
35 struct utimbuf
36 {
37   long actime;
38   long modtime;
39 };
40 #endif
41
42 /* Emulate utime (file, NULL) for systems (like 4.3BSD) that do not
43    interpret it to set the access and modification times of FILE to
44    the current time.  Return 0 if successful, -1 if not. */
45
46 static int
47 utime_null (const char *file)
48 {
49 #if HAVE_UTIMES_NULL
50   return utimes (file, 0);
51 #else
52   int fd;
53   char c;
54   int status = 0;
55   struct stat sb;
56
57   fd = open (file, O_RDWR);
58   if (fd < 0
59       || fstat (fd, &sb) < 0
60       || safe_read (fd, &c, sizeof (char)) < 0
61       || lseek (fd, (off_t) 0, SEEK_SET) < 0
62       || full_write (fd, &c, sizeof (char)) < 0
63       /* Maybe do this -- it's necessary on SunOS4.1.3 with some combination
64          of patches, but that system doesn't use this code: it has utimes.
65          || fsync (fd) < 0
66       */
67       || ftruncate (fd, st.st_size) < 0
68       || close (fd) < 0)
69     status = -1;
70   return status;
71 #endif
72 }
73
74 int
75 rpl_utime (const char *file, const struct utimbuf *times)
76 {
77   if (times)
78     return utime (file, times);
79
80   return utime_null (file);
81 }