- C Library - Home
- C Library - <assert.h>
- C Library - <complex.h>
- C Library - <ctype.h>
- C Library - <errno.h>
- C Library - <fenv.h>
- C Library - <float.h>
- C Library - <inttypes.h>
- C Library - <iso646.h>
- C Library - <limits.h>
- C Library - <locale.h>
- C Library - <math.h>
- C Library - <setjmp.h>
- C Library - <signal.h>
- C Library - <stdalign.h>
- C Library - <stdarg.h>
- C Library - <stdbool.h>
- C Library - <stddef.h>
- C Library - <stdio.h>
- C Library - <stdlib.h>
- C Library - <string.h>
- C Library - <tgmath.h>
- C Library - <time.h>
- C Library - <wctype.h>
- C Programming Resources
- C Programming - Tutorial
- C - Useful Resources
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