C programming fclose stdio.h

In C programming the <stdio.h> fclose causes the stream pointed to by stream to be flushed and the associated file to be closed.The declaration of the file is given below.

int fclose(FILE *stream);

stream -The file to be closed.

Return type
int -Returns zero is the stream was successfully closed or EOF if any errors were detected.

Some points to note:

i)When this function is called any unwritten buffered data for the stream are delivered to the host environment to be written to the file; any unread buffered data are discarded.

ii)Whether or not the call succeeds,the stream is disassociated from the file and any buffer set by the setbuf or setvbuf function is disassociated from the stream.

Code example

FILE *fp=fopen( “text.txt” , “w+” );

if( fp!=NULL )
/*Edit the file or do anything with the file */
printf( “File opening failed”);

fclose( fp ); //close the file

Why should you call fclose function?

It is a good programming practice to close a file as soon as you’ve finished with it.This protects any data from losing if any error occurs in any parts of the program and terminates the program in an abnormal way.Abnormal termination could result in the contents of the output buffer being lost, as the file wouldn’t be closed properly.

Another minor but relevant uses of ‘fclose’ is the number of files that can be opened simultaneously is limited. Closing the file as soon as you have finished working with it minimizes the chance of opening number of files larger than the threshold value and which may otherwise produce some sinister effect:the program may get hang or it may stop working or the program may terminate abruptly.