]> git.sur5r.net Git - cc65/blob - libsrc/common/fread.c
Copy TGI drivers into main lib dir
[cc65] / libsrc / common / fread.c
1 /*
2  * fread.c
3  *
4  * Ullrich von Bassewitz, 02.06.1998
5  */
6
7
8
9 #include <stdio.h>
10 #include <fcntl.h>
11 #include <errno.h>
12 #include "_file.h"
13
14
15
16 size_t fread (void* buf, size_t size, size_t count, FILE* f)
17 {
18     int bytes;
19
20     /* Is the file open? */
21     if ((f->f_flags & _FOPEN) == 0) {
22         _errno = EINVAL;                /* File not open */
23         return 0;
24     }
25
26     /* Did we have an error or EOF? */
27     if ((f->f_flags & (_FERROR | _FEOF)) != 0) {
28         /* Cannot read from stream */
29         return 0;
30     }
31
32     /* How many bytes to read? */
33     bytes = size * count;
34
35     if (bytes) {
36
37         /* Read the data. */
38         bytes = read (f->f_fd, buf, bytes);
39
40         switch (bytes) {
41
42             case -1:
43                 /* Read error */
44                 f->f_flags |= _FERROR;
45                 return 0;
46
47             case 0:
48                 /* End of file */
49                 f->f_flags |= _FEOF;
50                 /* FALLTHROUGH */
51
52             default:
53                 /* Unfortunately, we cannot avoid the divide here... */
54                 return bytes / size;
55         }
56
57     } else {
58
59         /* 0 bytes read */
60         return count;
61
62     }
63 }
64
65
66