xref: /original-bsd/lib/libc/stdio/fdopen.c (revision 7e7b101a)
1 /* @(#)fdopen.c	4.5 (Berkeley) 02/13/85 */
2 /*
3  * Unix routine to do an "fopen" on file descriptor
4  * The mode has to be repeated because you can't query its
5  * status
6  */
7 
8 #include <sys/types.h>
9 #include <sys/file.h>
10 #include <stdio.h>
11 
12 FILE *
13 fdopen(fd, mode)
14 	register char *mode;
15 {
16 	extern FILE *_findiop();
17 	static int nofile = -1;
18 	register FILE *iop;
19 
20 	if (nofile < 0)
21 		nofile = getdtablesize();
22 
23 	if (fd < 0 || fd >= nofile)
24 		return (NULL);
25 
26 	iop = _findiop();
27 	if (iop == NULL)
28 		return (NULL);
29 
30 	iop->_cnt = 0;
31 	iop->_file = fd;
32 	iop->_bufsiz = 0;
33 	iop->_base = iop->_ptr = NULL;
34 
35 	switch (*mode) {
36 	case 'r':
37 		iop->_flag = _IOREAD;
38 		break;
39 	case 'a':
40 		lseek(fd, (off_t)0, L_XTND);
41 		/* fall into ... */
42 	case 'w':
43 		iop->_flag = _IOWRT;
44 		break;
45 	default:
46 		return (NULL);
47 	}
48 
49 	if (mode[1] == '+')
50 		iop->_flag = _IORW;
51 
52 	return (iop);
53 }
54