We Have Your Record on File

Just as we found it helpful to group several related pieces of
data into a structure, we often find it useful to store
structures in files.
When we do this, we generally need to open the file as a binary
file.

For binary files, we use functions to read and write the file
different from
fprintf()
and
fscanf()
.
We use the functions
fwrite()
and
fread()
.
Suppose we have a structure in a variable called
new_stud
that
we want to write to a file called
new_student
.
We could do it with a code sequence like:

In each of these examples if we had defined a new type
with
typedef
and declared the structure to be of that type,
we would have used it in the
sizeof
instead of the
struct
designation.
For example, if we had a
typedef
creating a type called
student
instead of just having a structure tag called
student
, then we could do the write with:

fwrite(&new_stud, sizeof(student), 1, fp);

One other important point about these examples:
they do not do any error checking.
If we wanted to implement the
read_employee()
function so
that it would return a 1 if successful and a 0 if not, then
we could write it as: