File I/O in C: Engineering H192 - Computer Programming
File I/O in C: Engineering H192 - Computer Programming
File I/O in C
Lecture 7
Files in C
Files in C
• The statement:
FILE *fptr1, *fptr2 ;
declares that fptr1 and fptr2 are pointer variables of
type FILE. They will be assigned the address of a file
descriptor, that is, an area of memory that will be
associated with an input or output stream.
Opening Files
• The statement:
fptr1 = fopen ( "mydata", "r" ) ;
would open the file mydata for input (reading).
• The statement:
fptr2 = fopen ("results", "w" ) ;
would open the file results for output (writing).
• Once the files are open, they stay open until you close
them or end the program (which will close all files.)
int a, b ;
FILE *fptr1, *fptr2 ;
fptr1 = fopen ( "mydata", "r" ) ;
fscanf ( fptr1, "%d%d", &a, &b) ;
End of File
• The end-of-file indicator informs the program
when there are no more data (no more bytes) to
be processed.
• There are a number of ways to test for the end-of-
file condition. One is to use the feof function
which returns a true or false condition:
fscanf (fptr1, "%d", &var) ;
if ( feof (fptr1) )
{
printf ("End-of-file encountered.\n”);
}
Winter Quarter The Ohio State University Lect 7 P. 7
Gateway Engineering Education Coalition
Engineering H192 - Computer Programming
End of File
Writing To Files
int a = 5, b = 20 ;
FILE *fptr2 ;
fptr2 = fopen ( "results", "w" ) ;
fprintf ( fptr2, "%d %d\n", a, b ) ;
Closing Files
• The statements:
fclose ( fptr1 ) ;
fclose ( fptr2 ) ;
will close the files and release the file descriptor
space and I/O buffer memory.
printf ("%6.2f%2d%5.2f\n", a, b, c) ;
printf ("%6.2f,%2d,%5.2f\n", e, f, g) ;
}
12345678901234567890
****************************
13.72 5 6.68
13.72, 5, 6.68
Winter Quarter The Ohio State University Lect 7 P. 12
Gateway Engineering Education Coalition
Engineering H192 - Computer Programming