HP C/iX Library Reference Manual (30026-90004)
Chapter 5 171
HP C/iX Library Function Descriptions
fread
}
This program reads the employee information contained in the binary file empdata. The
data in this file consists of concatenated streams of bytes describing each employee in a
400-employee company. The bytes are written such that, when read correctly, they
correspond exactly with the emp structure defined in the program. The staff array is an
array of structures containing one structure for each employee.
In the fread() call, the sizeof(staff[0]) expression returns the number of bytes in the
emp structure. Because the same number of bytes are in each employee structure, any
element of the staff array can be specified as the sizeof argument; staff[0] is used in
this example. By counting the number of bytes in each structure member, you can
approximate the number of bytes returned by the sizeof operator (in this example, 40 +
40 + 8 + 6 + 2 + 4 = 100 bytes). This might vary due to padding performed by a
programming language or by machine architecture. Specifying EMPS as the
nitems
argument tells fread to read 400 structures. Thus, 100 x 400 = 40000 bytes are read,
filling in the information for the members of each structure contained in the staff array.
The fread() and fwrite() functions can read or write any type of data.
The following examples show some fread() calls that read different types of data:
To read a long integer:
long nint;
fread((void *)&nint, sizeof(nint), 1, stream);
To read an array of 100 long integers:
long nint[100];
fread((void *)nint, sizeof(nint[0]), 100, stream);
To read a double-precision floating-point value:
double fpoint;
fread((void *)&fpoint, sizeof(fpoint), 1, stream);
To read an array of 50 floating-point values:
float fpoint[50];
fread((void *)fpoint, sizeof(fpoint[0]), 50, stream);
See Also
fgetc(), getc(), gets(), getchar(), fscanf(), scanf(), ANSI C 4.9.8.1, POSIX.1 8.1