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:
fp = fopen("new_student", "wb");
fwrite(&new_stud, sizeof(struct student), 1, fp);
fclose(fp);
fwrite()
and
fread()
both take four arguments:
void read_employee(char name[], struct employee *emp)
{
FILE *fp;
fp = fopen(name, "rb");
fread(emp, sizeof(struct employee), 1, fp);
fclose(fp);
}
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:
int read_employee(char name[], struct employee *emp)
{
FILE *fp;
if((fp = fopen(name, "rb")) == NULL)
return 0;
if(fread(emp, sizeof(struct employee), 1, fp) == 0) {
fclose(fp);
return 0;
}
fclose(fp);
return 1;
}
struct video store[MAX_STOCK];