fclose() — Close file
Standards
| Standards / Extensions | C or C++ | Dependencies |
|---|---|---|
ISO C |
both |
Format
#include <stdio.h>
int fclose(FILE *stream);
General description
Flushes a stream, and then closes the file associated with that stream. Afterwards, the function releases any buffers associated with the stream. To flush means that unwritten buffered data is written to the file, and unread buffered data is discarded.
A pointer to a closed file cannot be used as an input value to the freopen() function.
Notes:
- The storage pointed to by the FILE pointer is freed by the fclose() function. An attempt to use the FILE pointer to a closed file is not valid. This restriction is true even when fclose() fails.
- If an application has locked a (FILE *) object (with flockfile() or ftrylockfile()), it is responsible for relinquishing the locked (FILE *) object (with funlockfile()) before calling fclose(). Failure to relinquish a locked (FILE *) object may cause deadlock (or looping).
Returned value
If successful closing the stream, fclose() returns 0.
If a failure occurs in flushing buffers or in outputting data, fclose() returns EOF. An attempt will still be made to close the file.
Special behavior for XPG4
fclose()
sets errno to one of the following values:
- Error Code
- Description
- EAGAIN
- The O_NONBLOCK flag is set and output cannot be written immediately.
- EBADF
- The underlying file descriptor is not valid.
- EFBIG
- Writing to the output file would exceed the maximum file size or the process's file size supported by the implementation.
- EINTR
- The fclose() function was interrupted by a signal before it had written any output.
- EIO
- The process is in a background process group and is attempting to write to its controlling terminal, but TOSTOP (defined in the termio.h include file) is set, the process is neither ignoring nor blocking SIGTTOU signals, and the process group of the process is orphaned.
- ENOSPC
- There is no free space left on the output device
- ENXIO
- A request was made of a nonexistent device, or the request was outside the device.
- EPIPE
- fclose() is trying to write to a pipe or FIFO that is not open for reading by any process. This error also generates a SIGPIPE signal.
Example
/* This example opens a file myfile.dat for reading as a stream and then
closes the file.
*/
#include <stdio.h>
int main(void)
{
FILE *stream;
stream = fopen("myfile.dat", "r");
⋮
if (fclose(stream)) /* Close the stream. */
printf("fclose error\n");
}
Related information
- See the topics about closing files and opening files in z/OS XL C/C++ Programming Guide
- stdio.h
- fopen() — Open a file
- freopen() — Redirect an open file