fclose()
PROTOTYPE
#include <stdio.h>
int fclose(FILE *file);
DESCRIPTION
fclose() frees the file control block identified by the handle file. After fclose() returns, file no longer references the file. If data was previously written to the file, some of it may still be in the volume’s data cache after fclose() returns. Closing a file does not flush its data to backing store.
To ensure all file changes (user data and metadata) are saved to backing store, either call fflush() or fsync() using the file descriptor or pointer before the file is closed, or call fflush(NULL), sync(), unmount(), or vsync() anytime.
On file systems that support links (RFS/XFS), if an open file is deleted, it can’t be reopened using its former path but deletion is delayed if the file has another link or is open via another handle. If the file being closed was previously deleted, has no other link, and no other open file descriptor or pointer, fclose() will both close the file and fully delete it.
If successful, fclose() returns 0. Otherwise, errno is set and -1 returned. If the file has unsaved changes and there is a preexisting fatal error when fclose() is called, it will set errno accordingly and return -1 but unless file is invalid, the file control block is always freed.
ERROR CODES
| EBADF | file is not the handle of an open file. |
| EBADFSYS | The file has unsaved changes and corruption has been detected. |
| EBITERR | The file has unsaved changes and error correction has failed. |
| EIO | The file has unsaved changes and a driver routine has failed. |
| ENOMEM | The file has unsaved changes and a critical memory allocation failed. |
| ENXIO | The file has unsaved changes and the volume has been removed. |
EXAMPLE
/*-------------------------------------------------------------*/
/* Close the file. Return -1 if error. */
/*-------------------------------------------------------------*/
if (fclose(file))
{
perror("fclose() failed");
return -1;
}