1 /* @(#)findfp.c 1.3 (Berkeley) 03/04/85 */ 2 #include <stdio.h> 3 4 #define active(iop) ((iop)->_flag & (_IOREAD|_IOWRT|_IORW)) 5 6 #define NSTATIC 3 /* stdin + stdout + stderr */ 7 8 FILE _iob[NSTATIC] = { 9 { 0, NULL, NULL, 0, _IOREAD, 0 }, /* stdin */ 10 { 0, NULL, NULL, 0, _IOWRT, 1 }, /* stdout */ 11 { 0, NULL, NULL, 0, _IOWRT|_IONBF, 2 }, /* stderr */ 12 }; 13 14 static FILE *_lastbuf = _iob + NSTATIC; 15 16 extern char *calloc(); 17 18 static FILE **iobglue; 19 static FILE **endglue; 20 static int nfiles; 21 22 FILE * 23 _findiop() 24 { 25 register FILE **iov; 26 register FILE *fp; 27 28 if (nfiles <= 0) 29 nfiles = getdtablesize(); 30 31 if (iobglue == NULL) { 32 iobglue = (FILE **)calloc(nfiles, sizeof *iobglue); 33 if (iobglue == NULL) 34 return (NULL); 35 36 endglue = iobglue + nfiles; 37 38 iov = iobglue; 39 for (fp = _iob; fp < _lastbuf; /* void */) 40 *iov++ = fp++; 41 } 42 43 iov = iobglue; 44 while (*iov != NULL && active(*iov)) 45 if (++iov >= endglue) 46 return (NULL); 47 48 if (*iov == NULL) 49 *iov = (FILE *)calloc(1, sizeof **iov); 50 51 return (*iov); 52 } 53 54 _fwalk(function) 55 register int (*function)(); 56 { 57 register FILE **iov; 58 register FILE *fp; 59 60 if (function == NULL) 61 return; 62 63 if (iobglue == NULL) { 64 for (fp = _iob; fp < _lastbuf; fp++) 65 if (active(fp)) 66 (*function)(fp); 67 } else { 68 for (iov = iobglue; iov < endglue; iov++) 69 if (*iov != NULL && active(*iov)) 70 (*function)(*iov); 71 } 72 } 73 74 _cleanup() 75 { 76 extern int fclose(); 77 78 _fwalk(fclose); 79 } 80