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