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