C Programming: Dealing with files (Part – 4)

We have discussed that ‘C’ provides buffered and un-buffered functions for file management. We have already discussed some of the buffered functions in our previous articles.

In this article, we will look into some of the un-buffered functions ‘C’ provides for handling files. Lets start this article with file open function.

“open” is an un-buffered file management function used to open or create files. The syntax of this function is:

int open(const char *pathname, int flags, mode_t mode);

Where pathname is the complete path of the file to open or create. flags controls the way to open or create a file; like open file in read only (O_RDONLY) more, open file in write only mode (O_WRONLY), create a file (O_CREAT) etc.,. Flags can be bitwise-or’d.

mode tells the permissions to use if the new file is created. These flags are valid only if O_CREAT flag is specified in flags parameter. mode flags are also bitwise-or’d.

Upon success “open” function will returns the file descriptor of the file. Other file management functions will use this file descriptor to do file management activities. If the function fails, it returns “-1”.

Below is an example “open” function call to create a file and provide full file access permissions to the owner. If the file already exists, the file contents will be erased.

   int fd = open("dummyfile.tmp", O_CREAT | O_TRUNC, S_IRWXU);

Once the file is opened, we should close the file. “close” function is used to close the previously opened file with “open” function. This is an important function. If you don’t call “close” upon open files, those files may be locked and can not be accessed by any other processes. This will become a problem, if multiple processes needs to access the same file.

The syntax of “close” function is very simple.

int close(int fd);

Where fd is the file descriptor of opened file. Upon success “close” function returns “0”; otherwise it returns “-1”.

Putting altogether here is the simple code.

// Sample.c
#include 

void main()
{
   int fd = open("dummyfile.tmp", O_CREAT | O_TRUNC, S_IRWXU);
   if ( fd > 0 )
   {
      close(fd);
   }
}

We will discuss about more functions in next articles…

// Malin

1 comment for “C Programming: Dealing with files (Part – 4)

Leave a Reply