1fread(3) Library Functions Manual fread(3)
2
3
4
6 fread, fwrite - binary stream input/output
7
9 Standard C library (libc, -lc)
10
12 #include <stdio.h>
13
14 size_t fread(void ptr[restrict .size * .nmemb],
15 size_t size, size_t nmemb,
16 FILE *restrict stream);
17 size_t fwrite(const void ptr[restrict .size * .nmemb],
18 size_t size, size_t nmemb,
19 FILE *restrict stream);
20
22 The function fread() reads nmemb items of data, each size bytes long,
23 from the stream pointed to by stream, storing them at the location
24 given by ptr.
25
26 The function fwrite() writes nmemb items of data, each size bytes long,
27 to the stream pointed to by stream, obtaining them from the location
28 given by ptr.
29
30 For nonlocking counterparts, see unlocked_stdio(3).
31
33 On success, fread() and fwrite() return the number of items read or
34 written. This number equals the number of bytes transferred only when
35 size is 1. If an error occurs, or the end of the file is reached, the
36 return value is a short item count (or zero).
37
38 The file position indicator for the stream is advanced by the number of
39 bytes successfully read or written.
40
41 fread() does not distinguish between end-of-file and error, and callers
42 must use feof(3) and ferror(3) to determine which occurred.
43
45 For an explanation of the terms used in this section, see at‐
46 tributes(7).
47
48 ┌────────────────────────────────────────────┬───────────────┬─────────┐
49 │Interface │ Attribute │ Value │
50 ├────────────────────────────────────────────┼───────────────┼─────────┤
51 │fread(), fwrite() │ Thread safety │ MT-Safe │
52 └────────────────────────────────────────────┴───────────────┴─────────┘
53
55 C11, POSIX.1-2008.
56
58 POSIX.1-2001, C89.
59
61 The program below demonstrates the use of fread() by parsing /bin/sh
62 ELF executable in binary mode and printing its magic and class:
63
64 $ ./a.out
65 ELF magic: 0x7f454c46
66 Class: 0x02
67
68 Program source
69
70 #include <stdio.h>
71 #include <stdlib.h>
72
73 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
74
75 int
76 main(void)
77 {
78 FILE *fp;
79 size_t ret;
80 unsigned char buffer[4];
81
82 fp = fopen("/bin/sh", "rb");
83 if (!fp) {
84 perror("fopen");
85 return EXIT_FAILURE;
86 }
87
88 ret = fread(buffer, sizeof(*buffer), ARRAY_SIZE(buffer), fp);
89 if (ret != ARRAY_SIZE(buffer)) {
90 fprintf(stderr, "fread() failed: %zu\n", ret);
91 exit(EXIT_FAILURE);
92 }
93
94 printf("ELF magic: %#04x%02x%02x%02x\n", buffer[0], buffer[1],
95 buffer[2], buffer[3]);
96
97 ret = fread(buffer, 1, 1, fp);
98 if (ret != 1) {
99 fprintf(stderr, "fread() failed: %zu\n", ret);
100 exit(EXIT_FAILURE);
101 }
102
103 printf("Class: %#04x\n", buffer[0]);
104
105 fclose(fp);
106
107 exit(EXIT_SUCCESS);
108 }
109
111 read(2), write(2), feof(3), ferror(3), unlocked_stdio(3)
112
113
114
115Linux man-pages 6.05 2023-07-20 fread(3)