rewrite core of the glob implementation for correctness & optimization
[musl.git] / src / stdio / fread.c
bloba2116da61370bd829c634353ad6f6fa6732d0d8b
1 #include "stdio_impl.h"
2 #include <string.h>
4 #define MIN(a,b) ((a)<(b) ? (a) : (b))
6 size_t fread(void *restrict destv, size_t size, size_t nmemb, FILE *restrict f)
8 unsigned char *dest = destv;
9 size_t len = size*nmemb, l = len, k;
10 if (!size) nmemb = 0;
12 FLOCK(f);
14 f->mode |= f->mode-1;
16 if (f->rpos != f->rend) {
17 /* First exhaust the buffer. */
18 k = MIN(f->rend - f->rpos, l);
19 memcpy(dest, f->rpos, k);
20 f->rpos += k;
21 dest += k;
22 l -= k;
25 /* Read the remainder directly */
26 for (; l; l-=k, dest+=k) {
27 k = __toread(f) ? 0 : f->read(f, dest, l);
28 if (!k) {
29 FUNLOCK(f);
30 return (len-l)/size;
34 FUNLOCK(f);
35 return nmemb;
38 weak_alias(fread, fread_unlocked);