1fread(3C) Standard C Library Functions fread(3C)
2
3
4
6 fread - binary input
7
9 #include <stdio.h>
10
11 size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream);
12
13
15 The fread() function reads into the array pointed to by ptr up to
16 nitems elements whose size is specified by size in bytes, from the
17 stream pointed to by stream. For each object, size calls are made to
18 the fgetc(3C) function and the results stored, in the order read, in an
19 array of unsigned char exactly overlaying the object. The file-position
20 indicator for the stream (if defined) is advanced by the number of
21 bytes successfully read. If an error occurs, the resulting value of the
22 file-position indicator for the stream is unspecified. If a partial
23 element is read, its value is unspecified.
24
25
26 The fread() function may mark the st_atime field of the file associated
27 with stream for update. The st_atime field will be marked for update by
28 the first successful execution of fgetc(3C), fgets(3C), fgetwc(3C),
29 fgetws(3C), fread(), fscanf(3C), getc(3C), getchar(3C), gets(3C), or
30 scanf(3C) using stream that returns data not supplied by a prior call
31 to ungetc(3C) or ungetwc(3C).
32
34 Upon successful completion, fread() returns the number of elements suc‐
35 cessfully read, which is less than nitems only if a read error or end-
36 of-file is encountered. If size or nitems is 0, fread() returns 0 and
37 the contents of the array and the state of the stream remain unchanged.
38 Otherwise, if a read error occurs, the error indicator for the stream
39 is set and errno is set to indicate the error.
40
42 Refer to fgetc(3C).
43
45 Example 1 Reading from a Stream
46
47
48 The following example reads a single element from the fp stream into
49 the array pointed to by buf.
50
51
52 #include <stdio.h>
53 ...
54 size_t bytes_read;
55 char buf[100];
56 FILE *fp;
57 ...
58 bytes_read = fread(buf, sizeof(buf), 1, fp);
59 ...
60
61
63 The ferror() or feof() functions must be used to distinguish between an
64 error condition and end-of-file condition. See ferror(3C).
65
66
67 Because of possible differences in element length and byte ordering,
68 files written using fwrite(3C) are application-dependent, and possibly
69 cannot be read using fread() by a different application or by the same
70 application on a different processor.
71
73 See attributes(5) for descriptions of the following attributes:
74
75
76
77
78 ┌─────────────────────────────┬─────────────────────────────┐
79 │ ATTRIBUTE TYPE │ ATTRIBUTE VALUE │
80 ├─────────────────────────────┼─────────────────────────────┤
81 │Interface Stability │Standard │
82 ├─────────────────────────────┼─────────────────────────────┤
83 │MT-Level │MT-Safe │
84 └─────────────────────────────┴─────────────────────────────┘
85
87 read(2), fclose(3C), ferror(3C), fopen(3C), getc(3C), gets(3C),
88 printf(3C), putc(3C), puts(3C), attributes(5), standards(5)
89
90
91
92SunOS 5.11 24 Jul 2002 fread(3C)