C programming stdio.h function - int fclose(FILE *stream)

‮//:sptth‬www.theitroad.com

In C programming, the stdio.h header file provides a set of functions for performing input and output operations on streams of data. One of the most important functions in this header file is fclose(), which closes a file stream that was previously opened using fopen() or a similar function.

The fclose() function takes one argument:

int fclose(FILE *stream);

The argument, stream, is a pointer to a FILE object that represents the file stream to be closed.

The fclose() function closes the file stream associated with the FILE object pointed to by stream. Any data that was buffered in memory is written to the file, and any resources associated with the file stream are released.

The function returns 0 on success, or EOF if an error occurred.

Here's an example of how to use fclose() to close a file stream:

#include <stdio.h>

int main() {
    FILE *fp;

    fp = fopen("example.txt", "w");
    if (fp == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    fprintf(fp, "Hello, world!\n");

    if (fclose(fp) != 0) {
        printf("Error closing file.\n");
        return 1;
    }

    return 0;
}

In the above example, the fopen() function is used to open a file named "example.txt" in write mode. The fprintf() function is then used to write the string "Hello, world!" to the file. Finally, the fclose() function is called to close the file stream, and check for any errors.