In order to read from a file we must first open the file using the function fopen(). fopen() takes two arguments, the name of the file to open and the mode in which to open the file. If we want to open the file to read from it, the mode we'll use is "r". If we want to write to a file, we'll open it with mode "w". There are many modes available and they are discussed in Chapter 11.
If fopen() manages to open the file sucessfully, it returns a file pointer (FILE*) which can then be used to access the contents of the file by passing it to fscanf() as shown in the example program below. If the file cannot be opened, then fopen() will return NULL. Whenever you attempt to open a file with fopen(), you'll need to check to see if the file was sucessfully opened. If the file couldn't be opened, then there is often nothing else your program can do and it's typical to print an error message and exit the program.
When we are finished using the file, we need to close it using the function fclose().
In the following example, the file contains only one number of type double.
/********************************************** ** File: fscanf1.c ** Author: Richard Chang ** Date: ?? ** Modified by: S. Evans ** Section: 01XX & 02XX ** EMail: bogar@cs.umbc.edu ** ** This program demonstrates opening a file ** reading from that file using the fscanf ** function, and closing the file. ** *********************************************/ #include <stdio.h> #include <stdlib.h> int main ( ) { double x ; FILE *ifp ; /* try to open the file */ ifp = fopen("test_data.dat", "r") ; /* make sure the file was opened */ if (ifp == NULL) { /* if it wasn't we can't run the rest of */ /* the program, so tell the user and quit */ printf ("Error opening test_data.dat\n"); exit (-1); } /* read one item from the file */ fscanf(ifp, "%lf", &x) ; /* you must close the file when finished reading */ fclose(ifp) ; /* check to see what you read */ printf("x = %.2f\n", x) ; return 0; }