Closing the File in C

When we have finished reading from the file, we need to close it. This is done using the function fclose( ) through the statement,

fclose ( fp ) ;

Once we close the file we can no longer read from it using getc( ) unless we reopen the file. Note that to close the file we don’t use the filename but the file pointer fp. On closing the file the buffer associated with the file is removed from memory.

Suppose we open a file with an intention to write characters into it. This time too a buffer would get associated with it.

When we attempt to write characters into this file using fputc( ) the characters would get written to the buffer.

When we close this file using fclose( ) three operations would be performed:

  • The characters in the buffer would be written to the file on the disk.
  • At the end of file a character with ASCII value 26 would get written.
  • The buffer would be eliminated from memory.
# include "stdio.h" 
main( ) 
 FILE *fp ; 
 char ch ; 
 fp = fopen ( "PR1.C", "r" ) ; 
 while ( 1 ) 
 ch = fgetc ( fp ) ; 
 if ( ch == EOF ) 
 break ; 
 printf ( "%c", ch ) ; 
 fclose ( fp ) ; 

Closing the File in C

Leave a Comment