exp2l: Work around a NetBSD 10.0/i386 bug.
[gnulib.git] / lib / truncate.c
blobff56da4dfce150f3c0474e538f8b41c3aa712425
1 /* truncate emulations for native Windows.
2 Copyright (C) 2017-2024 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, or (at your option)
7 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 along
15 with this program; if not, see <https://www.gnu.org/licenses/>. */
17 /* If the user's config.h happens to include <unistd.h>, let it include only
18 the system's <unistd.h> here, so that orig_faccessat doesn't recurse to
19 rpl_faccessat. */
20 #define _GL_INCLUDING_UNISTD_H
21 #include <config.h>
23 /* Specification. */
24 #include <unistd.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <string.h>
29 #include <sys/stat.h>
30 #undef _GL_INCLUDING_UNISTD_H
32 #if TRUNCATE_TRAILING_SLASH_BUG
33 static int
34 orig_truncate (const char *filename, off_t length)
36 return truncate (filename, length);
38 #endif
40 #ifdef __osf__
41 /* Write "unistd.h" here, not <unistd.h>, otherwise OSF/1 5.1 DTK cc
42 eliminates this include because of the preliminary #include <unistd.h>
43 above. */
44 # include "unistd.h"
45 #else
46 # include <unistd.h>
47 #endif
49 int
50 truncate (const char *filename, off_t length)
52 #if TRUNCATE_TRAILING_SLASH_BUG
53 /* Use the original truncate(), but correct the trailing slash handling. */
54 size_t len = strlen (filename);
55 if (len && filename[len - 1] == '/')
57 struct stat st;
58 if (stat (filename, &st) == 0)
59 errno = (S_ISDIR (st.st_mode) ? EISDIR : ENOTDIR);
60 return -1;
62 return orig_truncate (filename, length);
63 #else
64 int fd;
66 if (length == 0)
68 fd = open (filename, O_WRONLY | O_TRUNC | O_CLOEXEC);
69 if (fd < 0)
70 return -1;
72 else
74 fd = open (filename, O_WRONLY | O_CLOEXEC);
75 if (fd < 0)
76 return -1;
77 if (ftruncate (fd, length) < 0)
79 int saved_errno = errno;
80 close (fd);
81 errno = saved_errno;
82 return -1;
85 close (fd);
86 return 0;
87 #endif