vx32

Local 9vx git repository for patches.
git clone git://r-36.net/vx32
Log | Files | Refs

fread.c (996B)


      1 
      2 #include <string.h>
      3 #include <unistd.h>
      4 
      5 #include "ioprivate.h"
      6 
      7 size_t fread(void *ptr, size_t eltsize, size_t nelts, FILE *f)
      8 {
      9 	size_t totsize = eltsize * nelts;
     10 	size_t actsize = 0;
     11 
     12 	while (totsize > 0) {
     13 
     14 		size_t buffed = f->ilim - f->ipos;
     15 		if (totsize <= buffed) {
     16 
     17 			// The rest of the data we need is in the buffer.
     18 			memcpy(ptr, &f->ibuf[f->ipos], totsize);
     19 			f->ipos += totsize;
     20 			actsize += totsize;
     21 			goto done;
     22 		}
     23 
     24 		// Copy any remaining data we may have in the buffer.
     25 		memcpy(ptr, &f->ibuf[f->ipos], buffed);
     26 		f->ipos = f->ilim = 0;
     27 		ptr += buffed;
     28 		actsize += buffed;
     29 		totsize -= buffed;
     30 
     31 		// Don't use the buffer for large reads.
     32 		if (totsize >= BUFSIZ) {
     33 			ssize_t rc = read(f->fd, ptr, totsize);
     34 			if (rc < 0) {
     35 				f->errflag = 1;
     36 				goto done;
     37 			}
     38 			if (rc == 0) {
     39 				f->eofflag = 1;
     40 				goto done;
     41 			}
     42 			ptr += rc;
     43 			actsize += rc;
     44 			totsize -= rc;
     45 		} else {
     46 			if (__getinput(f) < 0)
     47 				goto done;
     48 		}
     49 	}
     50 
     51 done:
     52 	return actsize / eltsize;
     53 }
     54