For Your Eyes Only

Once we have a file open, we need to be able to put information into it and get information out of it. As implied when we talked about fopen() getting information out of a file is called reading the file and putting information into it is called writing the file. While we haven't realized it, we have been reading and writing a sort of "file" all along. There are versions of printf() and scanf() that will work on any file, not just the standard input and standard output ones. They are called fprintf() and fscanf() and we use them only on text files.

Suppose we wanted to put a line of text into a file that contained the name, ID number and GPA of student number i where each student is in a structure. We could use a statement like:

fprintf(fp, "%s %d %f\n", students[i].name,
   students[i].id, students[i].gpa);

Similarly, if we want to read a set of x,y coordinates from a file, we could use a statement like:
fscanf(fp, "%d%d", &x, &y);

The basic use of fprintf() and fscanf() is just as it is for printf() and scanf() . We just have to remember to put the file pointer variable as the first argument.

As a side note, in some implementations, printf(...) is just a shorthand for fprintf(stdout, ...) . They really use the same code.

Write a statement to read a string, an integer and a float from a file associated with the file variable file1 . Put the string into the array name , the integer into the variable id and the float into the variable salary .