tweak comment
[coreutils.git] / lib / ftruncate.c
blobadf87f64bb112cd851e7e903595f9410f795ba6f
1 /* ftruncate emulations that work on some System V's.
2 This file is in the public domain. */
4 #if HAVE_CONFIG_H
5 # include <config.h>
6 #endif
8 #include <sys/types.h>
9 #include <fcntl.h>
11 #ifdef F_CHSIZE
13 int
14 ftruncate (int fd, off_t length)
16 return fcntl (fd, F_CHSIZE, length);
19 #else /* not F_CHSIZE */
20 # ifdef F_FREESP
22 /* By William Kucharski <kucharsk@netcom.com>. */
24 # include <sys/stat.h>
25 # include <errno.h>
26 # if HAVE_UNISTD_H
27 # include <unistd.h>
28 # endif
30 int
31 ftruncate (int fd, off_t length)
33 struct flock fl;
34 struct stat filebuf;
36 if (fstat (fd, &filebuf) < 0)
37 return -1;
39 if (filebuf.st_size < length)
41 /* Extend file length. */
42 if (lseek (fd, (length - 1), SEEK_SET) < 0)
43 return -1;
45 /* Write a "0" byte. */
46 if (write (fd, "", 1) != 1)
47 return -1;
49 else
52 /* Truncate length. */
54 fl.l_whence = 0;
55 fl.l_len = 0;
56 fl.l_start = length;
57 fl.l_type = F_WRLCK; /* write lock on file space */
59 /* This relies on the *undocumented* F_FREESP argument to fcntl,
60 which truncates the file so that it ends at the position
61 indicated by fl.l_start. Will minor miracles never cease? */
63 if (fcntl (fd, F_FREESP, &fl) < 0)
64 return -1;
67 return 0;
70 # else /* not F_CHSIZE nor F_FREESP */
71 # if HAVE_CHSIZE
73 int
74 ftruncate (int fd, off_t length)
76 return chsize (fd, length);
79 # else /* not F_CHSIZE nor F_FREESP nor HAVE_CHSIZE */
81 # include <errno.h>
82 # ifndef errno
83 extern int errno;
84 # endif
86 int
87 ftruncate (int fd, off_t length)
89 errno = EIO;
90 return -1;
93 # endif /* not HAVE_CHSIZE */
94 # endif /* not F_FREESP */
95 #endif /* not F_CHSIZE */