Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - Closing files at a low level

Node:Closing files at a low level, Next:, 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.

 
 
  Published under free license. Design by Interspire