Closing Files

Instead of calling the sync system calls, you may

open()
your file with the
O_SYNC
flag, which will automatically flush changes. This is the same as calling
fsync()
after every call to
write()
!

Name:
close()
System call or function: System call Links: Online Manual | Course Packet
What it does: closes a file that was open with
open()
. It unmaps the open
fd
and disassociates the file from the program. The kernel is free to reuse this
fd
integer for other files that will be opened. Closing a file doesn't affect when the file is flushed to disk, but it may result in an unlinked file being finally physically erased from the disk. The most common error value is EIO, most likely indicating a low-level I/O error, but the file always gets closed.
What libraries you must include:
#include <unistd.h> // Defines close().
Syntax:
int close (int fd);
Description of arguments:
fd
: file descriptor of an open file
What type it returns:
int
On success:
0
On failure:
-1
If failure, does it set
errno
?
Yes
Quick example:
if (close (my_file_fd) == -1) perror("close");
Other variations: N/A