C Library - fclose() function



The C library fclose() function is used to close an open file stream. It closes the stream and all buffers are flushed.

Syntax

Following is the C library syntax of the fclose() function −

int fclose(FILE *stream);

Parameters

This function accepts only a single parameter −

  • *FILE stream: A pointer to a FILE object that identifies the stream to be closed. This pointer is obtained from functions like fopen, freopen, or tmpfile.

Return value

The function returns 0 if the file is successfully closed.It returns EOF (typically -1) if an error occurs while closing the file. The errno variable is set to indicate the error.

Example 1: Closing a File After Writing Data

This example shows how to write data to a file and then close the file using fclose.

Below is the demonstration of C library fclose() function.

#include <stdio.h>

int main() {
   FILE *file = fopen("example1.txt", "w");
   if (file == NULL) {
       perror("Error opening file");
       return 1;
   }
   fprintf(file, "Hello, World!\n");
   if (fclose(file) == EOF) {
       perror("Error closing file");
       return 1;
   }
   printf("File closed successfully.\n");
   return 0;
}


Output

The above code produces following result−

File closed successfully.

Example 2: Handling File Closing Error

This example handles the scenario where closing a file fails, demonstrating proper error handling.

#include <stdio.h>
#include <errno.h>

int main() {
   FILE *file = fopen("example3.txt", "w");
   if (file == NULL) {
       perror("Error opening file");
       return 1;
   }
   // Intentionally causing an error for demonstration (rare in practice)
   if (fclose(file) != 0) {
       perror("Error closing file");
       return 1;
   }
   // Trying to close the file again to cause an error
   if (fclose(file) == EOF) {
       perror("Error closing file");
       printf("Error code: %d\n", errno);
       return 1;
   }
   return 0;
}

Output

After execution of above code, we get the following result

Error closing file: Bad file descriptor
Error code: 9
Advertisements