xref: /csrg-svn/lib/libc/stdio/findfp.c (revision 21402)
1 /*
2  * Copyright (c) 1983 Regents of the University of California.
3  * All rights reserved.  The Berkeley software License Agreement
4  * specifies the terms and conditions for redistribution.
5  */
6 
7 #ifndef lint
8 static char sccsid[] = "@(#)findfp.c	5.1 (Berkeley) 05/30/85";
9 #endif not lint
10 
11 #include <stdio.h>
12 
13 #define active(iop)	((iop)->_flag & (_IOREAD|_IOWRT|_IORW))
14 
15 #define NSTATIC	3	/* stdin + stdout + stderr */
16 
17 FILE _iob[NSTATIC] = {
18 	{ 0, NULL, NULL, 0, _IOREAD,		0 },	/* stdin  */
19 	{ 0, NULL, NULL, 0, _IOWRT,		1 },	/* stdout */
20 	{ 0, NULL, NULL, 0, _IOWRT|_IONBF,	2 },	/* stderr */
21 };
22 
23 static	FILE	*_lastbuf = _iob + NSTATIC;
24 
25 extern	char	*calloc();
26 
27 static	FILE	**iobglue;
28 static	FILE	**endglue;
29 static	int	nfiles;
30 
31 FILE *
32 _findiop()
33 {
34 	register FILE **iov;
35 	register FILE *fp;
36 
37 	if (nfiles <= 0)
38 		nfiles = getdtablesize();
39 
40 	if (iobglue == NULL) {
41 		iobglue = (FILE **)calloc(nfiles, sizeof *iobglue);
42 		if (iobglue == NULL)
43 			return (NULL);
44 
45 		endglue = iobglue + nfiles;
46 
47 		iov = iobglue;
48 		for (fp = _iob; fp < _lastbuf; /* void */)
49 			*iov++ = fp++;
50 	}
51 
52 	iov = iobglue;
53 	while (*iov != NULL && active(*iov))
54 		if (++iov >= endglue)
55 			return (NULL);
56 
57 	if (*iov == NULL)
58 		*iov = (FILE *)calloc(1, sizeof **iov);
59 
60 	return (*iov);
61 }
62 
63 _fwalk(function)
64 	register int (*function)();
65 {
66 	register FILE **iov;
67 	register FILE *fp;
68 
69 	if (function == NULL)
70 		return;
71 
72 	if (iobglue == NULL) {
73 		for (fp = _iob; fp < _lastbuf; fp++)
74 			if (active(fp))
75 				(*function)(fp);
76 	} else {
77 		for (iov = iobglue; iov < endglue; iov++)
78 			if (*iov != NULL && active(*iov))
79 				(*function)(*iov);
80 	}
81 }
82 
83 _cleanup()
84 {
85 	extern int fclose();
86 
87 	_fwalk(fclose);
88 }
89