##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# fclose

From cppreference.com
< c‎ | io

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.

### [edit] Parameters

stream | - | the file stream to close

### [edit] Return value

​0​ on success, EOF otherwise

### [edit] Example

Run this code

    #include <stdio.h>
    #include <stdlib.h>

    int main(void)
    {
        FILE* fp = fopen("test.txt", "r");
        if(!fp) {
            perror("File opening failed");
            return EXIT_FAILURE;
        }

        int c; // note: int, not char, required to handle EOF
        while ((c = fgetc(fp)) != EOF) { // standard C I/O file reading loop
           putchar(c);
        }

        if (ferror(fp))
            puts("I/O error when reading");
        else if (feof(fp))
            puts("End of file reached successfully");

        fclose(fp);
    }

### [edit] References

- C11 standard (ISO/IEC 9899:2011):

  - 7.21.5.1 The fclose function (p: 304)

- C99 standard (ISO/IEC 9899:1999):

  - 7.19.5.1 The fclose function (p: 270)

- C89/C90 standard (ISO/IEC 9899:1990):

  - 4.9.5.1 The fclose function

### [edit] See also

fopen fopen_s (C11) | opens a file (function) [edit]
freopen freopen_s (C11) | open an existing stream with a different name (function) [edit]
C++ documentation for fclose

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=c/io/fclose&oldid=84359"