home *** CD-ROM | disk | FTP | other *** search
/ Club Amiga de Montreal - CAM / CAM_CD_1.iso / files / 387b.lha / dice_v2.02 / lib / stdio / fread.c < prev    next >
Encoding:
C/C++ Source or Header  |  1990-05-30  |  1.7 KB  |  94 lines

  1.  
  2. /*
  3.  *  FREAD.C
  4.  *
  5.  *  (c)Copyright 1990, Matthew Dillon, All Rights Reserved
  6.  *
  7.  *  fread does not return EOF unless an error occurs.  fread returns
  8.  *  0 or < elms when the end of file is reached.
  9.  */
  10.  
  11. #include <stdio.h>
  12.  
  13. #define buf ((char *)vbuf)
  14.  
  15. size_t
  16. fread(vbuf, elmsize, elms, fi)
  17. void *vbuf;
  18. size_t elmsize;
  19. size_t elms;
  20. FILE *fi;
  21. {
  22.     int bytes;
  23.     int origBytes;
  24.  
  25.     if (elmsize == 1)
  26.     bytes = elms;
  27.     else if (elms == 1)
  28.     bytes = elmsize;
  29.     else
  30.     bytes = elms * elmsize;
  31.  
  32.     origBytes = bytes;
  33.  
  34.     if (fi && (fi->sd_Flags & __SIF_READ) && !fi->sd_Error) {
  35.     int n = 0;    /*  actual read */
  36.  
  37.     if (bytes == 0 || (fi->sd_Flags & __SIF_EOF))
  38.         return(0);
  39.  
  40.     if (fi->sd_UC >= 0) {       /*  ungotten character */
  41.         *buf++ = fi->sd_UC;
  42.         fi->sd_UC = -1;
  43.         --bytes;
  44.     }
  45.  
  46.     if (fi->sd_RLeft > 0) {
  47.         n = (fi->sd_RLeft > bytes) ? bytes : fi->sd_RLeft;
  48.  
  49.         movmem(fi->sd_RPtr, buf, n);
  50.         fi->sd_RPtr += n;
  51.         fi->sd_RLeft -= n;
  52.         buf += n;
  53.         bytes -= n;
  54.     }
  55.     if (bytes) {
  56.         if (bytes < fi->sd_BufSiz) {
  57.         if (_filbuf(fi))        /*  on no more data return n    */
  58.             goto skip;
  59.         }
  60.         if (fi->sd_RLeft <= 0) {    /*  unbuffered read or too-large read */
  61.         int nn;
  62.  
  63.         nn = read(fi->sd_Fd, buf, bytes);
  64.         if (nn < 0) {
  65.             if (n == 0)
  66.             n = -1;
  67.         } else {
  68.             fi->sd_Offset += nn;
  69.             n += nn;
  70.         }
  71.         } else {
  72.         if (fi->sd_RLeft < bytes)
  73.             bytes = fi->sd_RLeft;
  74.         movmem(fi->sd_RPtr, buf, bytes);
  75.         fi->sd_RPtr += bytes;
  76.         fi->sd_RLeft -= bytes;
  77.         n += bytes;
  78.         }
  79.     }
  80. skip:
  81.     if (n < 0)
  82.         fi->sd_Error = EOF;
  83.     if (fi->sd_Error)
  84.         return(fi->sd_Error);
  85.     if (n == origBytes)
  86.         return(elms);
  87.     if (n == 0)
  88.         return(0);
  89.     return(n / elmsize);
  90.     }
  91.     return(EOF);
  92. }
  93.  
  94.