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:


fp = fopen("new_student", "wb");
fwrite(&new_stud, sizeof(struct student), 1, fp);
fclose(fp);

fwrite() and fread() both take four arguments:
  1. The first argument is a pointer to the data we want to write or to a place to put the data we're going to read.
  2. The second argument is the size of each item we're going to read or write.
  3. The third argument is the number of these items we're reading or writing. (For now we'll just use 1 here. In the next part , we'll look at working with more than one.)
  4. The last argument is the file pointer associated with the file we want to work with.
As another example, suppose we have a number of files that each contains an employee structure. We can write a function that loads one in given the name and a pointer to a place to put it.
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;
}

Let the array of videos be declared as:
struct video store[MAX_STOCK];
Write a statement to write the video structure number n of the array store to a file associated with the file variable file2 .