home *** CD-ROM | disk | FTP | other *** search
/ Programmer 7500 / MAX_PROGRAMMERS.iso / INFO / C / DLIBSSRC.ZIP / FDOPEN.C < prev    next >
Encoding:
C/C++ Source or Header  |  1987-10-03  |  1.8 KB  |  71 lines

  1. #include <osbind.h>
  2. #include <stdio.h>
  3. #include <io.h>
  4.  
  5. extern    FILE    _iob[];
  6.  
  7. FILE *fdopen(h, mode)
  8. register int h;
  9. register char *mode;
  10. /*
  11.  *    Associates a stream with the already open file <h>.  The <mode>
  12.  *    values are the same as for fopen(), but MUST be compatible with
  13.  *    the mode in which <h> was open()ed.  This functions allows use
  14.  *    of a file opened with the low level open()/creat() calls to be
  15.  *    used as a buffered/translated stream.  A pointer to a FILE struct
  16.  *    is returned, or NULL for errors.
  17.  */
  18. {
  19.     register FILE *fp = NULL;
  20.     register char *p = NULL;
  21.     register int i, j = FALSE, f = 0;
  22.     char *malloc();
  23.  
  24.     for(i=0; (!fp && (i < MAXFILES)); ++i)
  25.         if(!(_iob[i].F_stat & (F_READ | F_WRITE)))   /* empty slot? */
  26.             fp = &_iob[i];
  27.     if(!fp)
  28.         return(NULL);
  29.     while(*mode) {
  30.         switch(*mode++) {
  31.             case 'r':
  32.                 f |= F_READ;
  33.                 break;
  34.             case 'w':
  35.                 f |= F_WRITE;
  36.                 break;
  37.             case 'a':
  38.                 f |= F_WRITE;
  39.                 j = TRUE;
  40.                 break;
  41.             case '+':
  42.                 f |= (F_READ | F_WRITE);
  43.                 break;
  44.             case 'b':
  45.                 f |= F_BINARY;
  46.                 break;
  47.             case 't':
  48.                 f &= ~F_BINARY;
  49.                 break;
  50.             default:
  51.                 fputs(stderr, "Illegal file mode.\n");
  52.                 return(NULL);
  53.         }
  54.     }
  55.     if((i = (f & (F_READ | F_WRITE))) == 0)
  56.         return(NULL);
  57.     if((p=malloc(BUFSIZ)) != NULL)    /* set up file buffer */
  58.         f |= F_BUFFER;
  59.     if(j)                /* append mode. move to eof. */
  60.         lseek(h, 0L, _LSKend);
  61.     fp->F_h = h;            /* file handle */
  62.     fp->F_stat = f;            /* file status flags */
  63.     fp->F_buf = p;            /* base of file buffer */
  64.     fp->F_bp = p;            /* current buffer pointer */
  65.     fp->F_bsiz = (p ? BUFSIZ : 0);    /* buffer size */
  66.     fp->F_cnt = 0;            /* # of bytes in buffer */
  67.     fp->F_unc1 = '\0';        /* primary ungotten character */
  68.     fp->F_unc2 = '\0';        /* secondary ungotten character */
  69.     return(fp);
  70. }
  71.