]> git.sur5r.net Git - cc65/blob - libsrc/common/fread.c
Use macpack for debugging, cosmetic changes
[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 (size_t) -1;
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         /* Read the data. */
37         bytes = read (f->f_fd, buf, bytes);
38         if (bytes == -1) {
39             /* Read error */
40             f->f_flags |= _FERROR;
41             return (size_t) -1;
42         }
43         if (bytes == 0) {
44             /* End of file */
45             f->f_flags |= _FEOF;
46             return (size_t) -1;
47         }
48
49         /* Unfortunately, we cannot avoid the divide here... */
50         return bytes / size;
51
52     } else {
53
54         /* 0 bytes read */
55         return count;
56
57     }
58 }
59
60
61