1 /* ftruncate emulations that work on some System V's.
2 This file is in the public domain. */
4 /* Copyright 2012 Free Software Foundation, Inc.
6 This file is part of gold.
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21 MA 02110-1301, USA. */
28 #include <sys/types.h>
31 extern int ftruncate (int, off_t);
36 ftruncate (int fd, off_t length)
38 return fcntl (fd, F_CHSIZE, length);
41 #else /* not F_CHSIZE */
44 /* By William Kucharski <kucharsk@netcom.com>. */
46 # include <sys/stat.h>
50 ftruncate (int fd, off_t length)
55 if (fstat (fd, &filebuf) < 0)
58 if (filebuf.st_size < length)
60 /* Extend file length. */
61 if (lseek (fd, (length - 1), SEEK_SET) < 0)
64 /* Write a "0" byte. */
65 if (write (fd, "", 1) != 1)
71 /* Truncate length. */
76 fl.l_type = F_WRLCK; /* write lock on file space */
78 /* This relies on the *undocumented* F_FREESP argument to fcntl,
79 which truncates the file so that it ends at the position
80 indicated by fl.l_start. Will minor miracles never cease? */
82 if (fcntl (fd, F_FREESP, &fl) < 0)
89 # else /* not F_CHSIZE nor F_FREESP */
90 # if HAVE_CHSIZE /* native Windows, e.g. mingw */
93 ftruncate (int fd, off_t length)
95 return chsize (fd, length);
98 # else /* not F_CHSIZE nor F_FREESP nor HAVE_CHSIZE */
103 ftruncate (int fd, off_t length)
109 # endif /* not HAVE_CHSIZE */
110 # endif /* not F_FREESP */
111 #endif /* not F_CHSIZE */