FILE INPUT/OUTPUT
To work with files, the library routines must be included into
your programs. This is done by the statement,
#include <stdio.h>
as the first statement of your program.
USING FILES
FILE is a predefined type. You declare a variable of this type as
FILE *in_file;
This declares infile to be a pointer to a file.
in_file = fopen( "myfile.dat", "r" );
In this example, the file myfile.dat in the current directory is opened for read access.
fclose( in_file );
The following illustrates the fopen function, and adds testing to see if the file was opened successfully.
#include <stdio.h>
/* declares pointers to an input file, and the fopen function */
FILE *input_file, *fopen ();
/* the pointer of the input file is assigned the value returned from the fopen call. */
/* fopen tries to open a file called datain for read only. Note that */
/* "w" = write, and "a" = append. */
input_file = fopen("datain", "r");
/* The pointer is now checked. If the file was opened, it will point to the first */
/* character of the file. If not, it will contain a NULL or 0. */
if( input_file == NULL ) {
printf("*** datain could not be opened.\n");
printf("returning to dos.\n");
exit(1);
}
NOTE: Consider the following statement, which combines the opening of the file and its test to see if it was successfully opened into a single statement.
if(( input_file = fopen ("datain", "r" )) == NULL ) {
printf("*** datain could not be opened.\n");
printf("returning to dos.\n");
exit(1);
}