fstat: Fix module dependency conditions.
[gnulib/ericb.git] / lib / fstat.c
blobd2e04688f253cef87104192134355e0e99360d6c
1 /* fstat() replacement.
2 Copyright (C) 2011-2017 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* If the user's config.h happens to include <sys/stat.h>, let it include only
18 the system's <sys/stat.h> here, so that orig_fstat doesn't recurse to
19 rpl_fstat. */
20 #define __need_system_sys_stat_h
21 #include <config.h>
23 /* Get the original definition of fstat. It might be defined as a macro. */
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #undef __need_system_sys_stat_h
28 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
29 # define WINDOWS_NATIVE
30 #endif
32 #if !defined WINDOWS_NATIVE
34 static int
35 orig_fstat (int fd, struct stat *buf)
37 return fstat (fd, buf);
40 #endif
42 /* Specification. */
43 /* Write "sys/stat.h" here, not <sys/stat.h>, otherwise OSF/1 5.1 DTK cc
44 eliminates this include because of the preliminary #include <sys/stat.h>
45 above. */
46 #include "sys/stat.h"
48 #include <errno.h>
49 #include <unistd.h>
50 #ifdef WINDOWS_NATIVE
51 # define WIN32_LEAN_AND_MEAN
52 # include <windows.h>
53 # if GNULIB_MSVC_NOTHROW
54 # include "msvc-nothrow.h"
55 # else
56 # include <io.h>
57 # endif
58 # include "stat-w32.h"
59 #endif
61 int
62 rpl_fstat (int fd, struct stat *buf)
64 #if REPLACE_FCHDIR && REPLACE_OPEN_DIRECTORY
65 /* Handle the case when rpl_open() used a dummy file descriptor to work
66 around an open() that can't normally visit directories. */
67 const char *name = _gl_directory_name (fd);
68 if (name != NULL)
69 return stat (name, buf);
70 #endif
72 #ifdef WINDOWS_NATIVE
73 /* Fill the fields ourselves, because the original fstat function returns
74 values for st_atime, st_mtime, st_ctime that depend on the current time
75 zone. See
76 <https://lists.gnu.org/archive/html/bug-gnulib/2017-04/msg00134.html> */
77 HANDLE h = (HANDLE) _get_osfhandle (fd);
79 if (h == INVALID_HANDLE_VALUE)
81 errno = EBADF;
82 return -1;
84 return _gl_fstat_by_handle (h, NULL, buf);
85 #else
86 return orig_fstat (fd, buf);
87 #endif