A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/c_standard_library/c_function_fclose.htm below:

C Standard Library fclose Function

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 −

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

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4