Node:Closing files at a low level, Next:Reading files at a low level, Previous:Opening files at a low level, Up:Low-level file routines
Closing files at a low level
To close a file descriptor, use the low-level file function
close
. The sole argument to close
is the file descriptor
you wish to close.
The close
function returns 0 if the call was successful, and -1
if there was an error. In addition to the usual file name error codes,
it can set the system variable errno
to one of the following
values. It can also set errno
to several other values, mostly of
interest to advanced C programmers. See Opening and Closing Files,
for more information.
EBADF
- The file descriptor passed to
close
is not valid.
Remember, close a stream by using fclose
instead. This allows
the necessary system bookkeeping to take place before the file is
closed.
Here is a code example using both the low-level file functions
open
and close
.
#include <stdio.h> #include <fcntl.h> int main() { char my_filename[] = "snazzyjazz17.txt"; int my_file_descriptor, close_err; /* Open my_filename for writing. Create it if it does not exist. Do not clobber it if it does. */ my_file_descriptor = open (my_filename, O_WRONLY | O_CREAT | O_EXCL); if (my_file_descriptor == -1) { printf ("Open failed.\n"); } close_err = close (my_file_descriptor); if (close_err == -1) { printf ("Close failed.\n"); } return 0; }
Running the above code example for the first time should produce no
errors, and should create an empty text file called
snazzyjazz17.txt
. Running it a second time should display the
following errors on your monitor, since the file snazzyjazz17.txt
already exists, and should not be clobbered according to the flags
passed to open
.
Open failed. Close failed.