Defined in header <stdio.h>
int fclose( FILE *stream );

Closes the given file stream. Any unwritten buffered data are flushed to the OS. Any unread buffered data are discarded.

Whether or not the operation succeeds, the stream is no longer associated with a file, and the buffer allocated by setbuf or setvbuf, if any, is also disassociated and deallocated if automatic allocation was used.

The behavior is undefined if the value of the pointer stream is used after fclose returns.


stream - the file stream to close

Return value

​0​ on success, EOF otherwise.


#include <stdio.h>
#include <stdlib.h>
int main(void)
    int is_ok = EXIT_FAILURE;
    const char* fname = "/tmp/unique_name.txt"; // or tmpnam(NULL);
    FILE* fp = fopen(fname, "w+");
    if(!fp) {
        perror("File opening failed");
        return is_ok;
    fputs("Hello, world!\n", fp);
    int c; // note: int, not char, required to handle EOF
    while ((c = fgetc(fp)) != EOF) { // standard C I/O file reading loop
    if (ferror(fp)) {
        puts("I/O error when reading");
    } else if (feof(fp)) {
        puts("End of file reached successfully");
        is_ok = EXIT_SUCCESS;
    return is_ok;

Possible output:

Hello, world!
End of file reached successfully


  • C11 standard (ISO/IEC 9899:2011):
    • The fclose function (p: 304)
  • C99 standard (ISO/IEC 9899:1999):
    • The fclose function (p: 270)
  • C89/C90 standard (ISO/IEC 9899:1990):
    • The fclose function

See also

opens a file
open an existing stream with a different name
C++ documentation for fclose

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.