fix various bugs in new integer parser framework
[musl] / src / stdio / fread.c
1 #include "stdio_impl.h"
2
3 #define MIN(a,b) ((a)<(b) ? (a) : (b))
4
5 size_t fread(void *destv, size_t size, size_t nmemb, FILE *f)
6 {
7         unsigned char *dest = destv;
8         size_t len = size*nmemb, l = len, k;
9
10         /* Never touch the file if length is zero.. */
11         if (!l) return 0;
12
13         FLOCK(f);
14
15         if (f->rend - f->rpos > 0) {
16                 /* First exhaust the buffer. */
17                 k = MIN(f->rend - f->rpos, l);
18                 memcpy(dest, f->rpos, k);
19                 f->rpos += k;
20                 dest += k;
21                 l -= k;
22         }
23         
24         if (!l) {
25                 FUNLOCK(f);
26                 return nmemb;
27         }
28
29         /* Read the remainder directly */
30         for (; l; l-=k, dest+=k) {
31                 k = f->read(f, dest, l);
32                 if (k+1<=1) {
33                         FUNLOCK(f);
34                         return (len-l)/size;
35                 }
36         }
37
38         FUNLOCK(f);
39         return nmemb;
40 }
41
42 weak_alias(fread, fread_unlocked);