C Standard Library

C <stdio.h> - fclose() Function



The C <stdio.h> fclose() function is used to close the given file stream. Any unwritten buffered data are flushed. Any unread buffered data are discarded.

Even if the call fails, the stream and its buffers are no longer associated with the file. The behavior is undefined if the value of the pointer stream is used after the call.

Syntax

int fclose ( FILE * stream );

Parameters

stream Specify a pointer to a FILE object that specifies the stream to be closed.

Return Value

Returns 0 if the file is successfully closed, otherwise EOF is returned.

Example:

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, file is opened using fopen. If the first character in the file is not EOF, it will read the file until EOF is reached. After performing the operation, it is closed using fclose() function.

#include <stdio.h>
 
int main (){
  //open the file in read mode
  FILE *pFile = fopen("test.txt", "r");
  
  //first character in the file
  int c = getc(pFile);
  
  //if first character is not EOF, reads and writes
  //characters from the file until EOF is reached
  while (c != EOF) {
    putchar(c);
    c = getc(pFile);
  }
  
  //close the file
  fclose(pFile);
  return 0;
}

The output of the above code will be:

This is a test file.
It contains dummy content.

❮ C <stdio.h> Library