1*0Sstevel@tonic-gate /*
2*0Sstevel@tonic-gate  * Copyright (c) 1997-2000 by Sun Microsystems, Inc.
3*0Sstevel@tonic-gate  * All rights reserved.
4*0Sstevel@tonic-gate  */
5*0Sstevel@tonic-gate 
6*0Sstevel@tonic-gate #ifndef LINT
7*0Sstevel@tonic-gate static const char rcsid[] = "$Id: ftruncate.c,v 8.4 1999/10/13 16:39:21 vixie Exp $";
8*0Sstevel@tonic-gate #endif
9*0Sstevel@tonic-gate 
10*0Sstevel@tonic-gate #pragma ident	"%Z%%M%	%I%	%E% SMI"
11*0Sstevel@tonic-gate 
12*0Sstevel@tonic-gate /*
13*0Sstevel@tonic-gate  * ftruncate - set file size, BSD Style
14*0Sstevel@tonic-gate  *
15*0Sstevel@tonic-gate  * shortens or enlarges the file as neeeded
16*0Sstevel@tonic-gate  * uses some undocumented locking call. It is known to work on SCO unix,
17*0Sstevel@tonic-gate  * other vendors should try.
18*0Sstevel@tonic-gate  * The #error directive prevents unsupported OSes
19*0Sstevel@tonic-gate  */
20*0Sstevel@tonic-gate 
21*0Sstevel@tonic-gate #include "port_before.h"
22*0Sstevel@tonic-gate 
23*0Sstevel@tonic-gate #if defined(M_UNIX)
24*0Sstevel@tonic-gate #define OWN_FTRUNCATE
25*0Sstevel@tonic-gate #include <stdio.h>
26*0Sstevel@tonic-gate #ifdef _XOPEN_SOURCE
27*0Sstevel@tonic-gate #undef _XOPEN_SOURCE
28*0Sstevel@tonic-gate #endif
29*0Sstevel@tonic-gate #ifdef _POSIX_SOURCE
30*0Sstevel@tonic-gate #undef _POSIX_SOURCE
31*0Sstevel@tonic-gate #endif
32*0Sstevel@tonic-gate 
33*0Sstevel@tonic-gate #include <fcntl.h>
34*0Sstevel@tonic-gate 
35*0Sstevel@tonic-gate #include "port_after.h"
36*0Sstevel@tonic-gate 
37*0Sstevel@tonic-gate int
38*0Sstevel@tonic-gate __ftruncate(int fd, long wantsize) {
39*0Sstevel@tonic-gate 	long cursize;
40*0Sstevel@tonic-gate 
41*0Sstevel@tonic-gate 	/* determine current file size */
42*0Sstevel@tonic-gate 	if ((cursize = lseek(fd, 0L, 2)) == -1)
43*0Sstevel@tonic-gate 		return (-1);
44*0Sstevel@tonic-gate 
45*0Sstevel@tonic-gate 	/* maybe lengthen... */
46*0Sstevel@tonic-gate 	if (cursize < wantsize) {
47*0Sstevel@tonic-gate 		if (lseek(fd, wantsize - 1, 0) == -1 ||
48*0Sstevel@tonic-gate 		    write(fd, "", 1) == -1) {
49*0Sstevel@tonic-gate 			return (-1);
50*0Sstevel@tonic-gate 		}
51*0Sstevel@tonic-gate 		return (0);
52*0Sstevel@tonic-gate 	}
53*0Sstevel@tonic-gate 
54*0Sstevel@tonic-gate 	/* maybe shorten... */
55*0Sstevel@tonic-gate 	if (wantsize < cursize) {
56*0Sstevel@tonic-gate 		struct flock fl;
57*0Sstevel@tonic-gate 
58*0Sstevel@tonic-gate 		fl.l_whence = 0;
59*0Sstevel@tonic-gate 		fl.l_len = 0;
60*0Sstevel@tonic-gate 		fl.l_start = wantsize;
61*0Sstevel@tonic-gate 		fl.l_type = F_WRLCK;
62*0Sstevel@tonic-gate 		return (fcntl(fd, F_FREESP, &fl));
63*0Sstevel@tonic-gate 	}
64*0Sstevel@tonic-gate 	return (0);
65*0Sstevel@tonic-gate }
66*0Sstevel@tonic-gate #endif
67*0Sstevel@tonic-gate 
68*0Sstevel@tonic-gate #ifndef OWN_FTRUNCATE
69*0Sstevel@tonic-gate int __bindcompat_ftruncate;
70*0Sstevel@tonic-gate #endif
71