Commit | Line | Data |
---|---|---|
639aed4c KB |
1 | /*- |
2 | * Copyright (c) 1990 The Regents of the University of California. | |
3 | * All rights reserved. | |
4 | * | |
5 | * This code is derived from software contributed to Berkeley by | |
6 | * Chris Torek. | |
7 | * | |
8 | * %sccs.include.redist.c% | |
586c39b1 DF |
9 | */ |
10 | ||
2ce81398 | 11 | #if defined(LIBC_SCCS) && !defined(lint) |
cb631443 | 12 | static char sccsid[] = "@(#)fdopen.c 5.6 (Berkeley) %G%"; |
639aed4c | 13 | #endif /* LIBC_SCCS and not lint */ |
39195eb1 | 14 | |
41e01b3e | 15 | #include <sys/types.h> |
cb631443 KB |
16 | #include <fcntl.h> |
17 | #include <unistd.h> | |
41e01b3e | 18 | #include <stdio.h> |
dacc684e | 19 | #include <errno.h> |
639aed4c | 20 | #include "local.h" |
39195eb1 BJ |
21 | |
22 | FILE * | |
23 | fdopen(fd, mode) | |
639aed4c | 24 | int fd; |
d25ccb19 | 25 | const char *mode; |
39195eb1 | 26 | { |
639aed4c | 27 | register FILE *fp; |
dacc684e KB |
28 | static int nofile; |
29 | int flags, oflags, fdflags, tmp; | |
39195eb1 | 30 | |
639aed4c | 31 | if (nofile == 0) |
41e01b3e S |
32 | nofile = getdtablesize(); |
33 | ||
dacc684e | 34 | if ((flags = __sflags(mode, &oflags)) == 0) |
639aed4c KB |
35 | return (NULL); |
36 | ||
37 | /* Make sure the mode the user wants is a subset of the actual mode. */ | |
dacc684e KB |
38 | if ((fdflags = fcntl(fd, F_GETFL, 0)) < 0) |
39 | return (NULL); | |
40 | tmp = fdflags & O_ACCMODE; | |
41 | if (tmp != O_RDWR && (tmp != (oflags & O_ACCMODE))) { | |
639aed4c | 42 | errno = EINVAL; |
41e01b3e | 43 | return (NULL); |
639aed4c | 44 | } |
41e01b3e | 45 | |
639aed4c | 46 | if ((fp = __sfp()) == NULL) |
c72d2806 | 47 | return (NULL); |
dacc684e | 48 | fp->_flags = flags; |
639aed4c KB |
49 | /* |
50 | * If opened for appending, but underlying descriptor does not have | |
51 | * O_APPEND bit set, assert __SAPP so that __swrite() will lseek to | |
52 | * end before each write. | |
53 | */ | |
54 | if ((oflags & O_APPEND) && !(fdflags & O_APPEND)) | |
55 | fp->_flags |= __SAPP; | |
639aed4c KB |
56 | fp->_file = fd; |
57 | fp->_cookie = fp; | |
58 | fp->_read = __sread; | |
59 | fp->_write = __swrite; | |
60 | fp->_seek = __sseek; | |
61 | fp->_close = __sclose; | |
62 | return (fp); | |
39195eb1 | 63 | } |