integer_length_ll: Optimize for MSVC in 32-bit mode.
[gnulib.git] / lib / truncate.c
blobb04f7c784155dfaa79080758201c7fe1bd04759a
1 /* truncate emulations for native Windows.
2 Copyright (C) 2017-2020 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 #include <config.h>
19 /* Specification. */
20 #include <unistd.h>
22 #include <errno.h>
23 #include <fcntl.h>
25 int
26 truncate (const char *filename, off_t length)
28 int fd;
30 if (length == 0)
32 fd = open (filename, O_WRONLY | O_TRUNC | O_CLOEXEC);
33 if (fd < 0)
34 return -1;
36 else
38 fd = open (filename, O_WRONLY | O_CLOEXEC);
39 if (fd < 0)
40 return -1;
41 if (ftruncate (fd, length) < 0)
43 int saved_errno = errno;
44 close (fd);
45 errno = saved_errno;
46 return -1;
49 close (fd);
50 return 0;