.
[gnulib.git] / lib / ftruncate.c
1 /* ftruncate emulations that work on some System V's.
2    This file is in the public domain.  */
3
4 #ifdef HAVE_CONFIG_H
5 #if defined (CONFIG_BROKETS)
6 /* We use <config.h> instead of "config.h" so that a compilation
7    using -I. -I$srcdir will use ./config.h rather than $srcdir/config.h
8    (which it would do because it found this file in $srcdir).  */
9 #include <config.h>
10 #else
11 #include "config.h"
12 #endif
13 #endif
14
15 #include <sys/types.h>
16 #include <fcntl.h>
17
18 #include <errno.h>
19 #ifndef STDC_HEADERS
20 extern int errno;
21 #endif
22
23 #ifdef F_CHSIZE
24
25 int
26 ftruncate (fd, length)
27      int fd;
28      off_t length;
29 {
30   return fcntl (fd, F_CHSIZE, length);
31 }
32
33 #else /* not F_CHSIZE */
34 #ifdef F_FREESP
35
36 /* By William Kucharski <kucharsk@netcom.com>.  */
37
38 #include <sys/stat.h>
39
40 #ifdef HAVE_UNISTD_H
41 #include <unistd.h>
42 #endif
43
44 int
45 ftruncate (fd, length)
46      int fd;
47      off_t length;
48 {
49   struct flock fl;
50   struct stat filebuf;
51
52   if (fstat (fd, &filebuf) < 0)
53     return -1;
54
55   if (filebuf.st_size < length)
56     {
57       /* Extend file length. */
58       if (lseek (fd, (length - 1), SEEK_SET) < 0)
59         return -1;
60
61       /* Write a "0" byte. */
62       if (write (fd, "", 1) != 1)
63         return -1;
64     }
65   else
66     {
67
68       /* Truncate length. */
69
70       fl.l_whence = 0;
71       fl.l_len = 0;
72       fl.l_start = length;
73       fl.l_type = F_WRLCK;      /* write lock on file space */
74
75       /* This relies on the *undocumented* F_FREESP argument to fcntl,
76          which truncates the file so that it ends at the position
77          indicated by fl.l_start.  Will minor miracles never cease?  */
78
79       if (fcntl (fd, F_FREESP, &fl) < 0)
80         return -1;
81     }
82
83   return 0;
84 }
85
86 #else /* not F_CHSIZE nor F_FREESP */
87 #ifdef HAVE_CHSIZE
88
89 int
90 ftruncate (fd, length)
91      int fd;
92      off_t length;
93 {
94   return chsize (fd, length);
95 }
96
97 #else /* not F_CHSIZE nor F_FREESP nor HAVE_CHSIZE */
98
99 int
100 ftruncate (fd, length)
101      int fd;
102      off_t length;
103 {
104   errno = EIO;
105   return -1;
106 }
107
108 #endif /* not HAVE_CHSIZE */
109 #endif /* not F_FREESP */
110 #endif /* not F_CHSIZE */