The functions fscanf and fprintf become interesting, of course,
when you provide as their first arguments file pointers other than stdin
and stdout. Take a look at io3.c to
see how that is done.
Notice that we have declared a variable called outfile whose type is
FILE*. (This syntax means that outfile is a pointer to a FILE.)
We have also given outfile a value so that it points to a particular
file. We have done this by calling the function fopen, which takes as
arguments the name of the file to which it should write and the string
"w", which tells C that we wish to write to (as opposed to read from) the
file.
Before we start using outfile, we must first check to make sure that the
file pointer was successfully created. If there was a problem opening the
desired file for writing, the value of outfile will be NULL (which is a
constant defined in ``stdio.h'') and we should not attempt to use the value
further. Always do this kind of check whenever you open a file!
Once we are sure that outfile contains a valid file pointer, we can use
it as the first argument to fprintf, just as we used stdout in the
previous example. If you run the program, you will see that no visible output
is produced. Where did it go?
Click here for the answer
Suppose that you wanted to write to a file other than ``result.txt''. What
would you have to change about the program?
Click here for the answer
Notice one final point about the example program. When we are finished writing
to a file, we close it by calling fclose. You should get into the habit
of closing all files that you open.
Joseph L. Zachary
Hamlet Project
Department of Computer Science
University of Utah