This blog is under construction

Tuesday, 22 May 2012

File Descriptors in C

File descriptor is a number.  Whenever we create a new file using creat() function or open an existing file using open() function, a file descriptor is returned by kernel to the process.  So, we can identify the file to which we want to read or write using file descriptors.

The following are the unix shell's association with file descriptors:

 File descriptors  Symbolic constants  Detail
 0  STDIN_FILENO  Standard Input
 1  STDOUT_FILENO  Standard Output
 2  STDERR_FILENO  Standard Error

int open(const char  *path, int oflag, mode_t mode)
Opens file at the given path for read or write operation.  Here, oflag denotes how the file is to opened and mode indicates the access permission information.

ssize_t read(int fd, void *buf, size_t nbytes)
Reads nbytes of data from the file referred by the file descriptor fd and writes them to the buffer buf. Returns 0 if no data is read, otherwise returns the number of byte read.

ssize_t write(int fd, const void *buf, size_t nbytes)
Writes nbytes of data from the buffer buf to the file referred by the file descriptor fd.

File descriptor example in C:

  int main() {
        int fd, num;
        char str[100];
        fd = open("input.txt", O_RDONLY, 0);  // fd is file descriptor
        // read data from the file referred by fd and writes it to str
        while ((num = read(fd, str, 10)) > 0) {
                // writes str to standard output
                write(1, str, num);  // num is no of bytes read
        return 0;

  jp@jp-VirtualBox:~/$ cat input.txt 
  hello world
  hello world
  hello world
  hello world
  jp@jp-VirtualBox:~/$ ./a.out
  hello world
  hello world
  hello world
  hello world

File number(descriptor) can also be obtained using another built-in function fileno()

No comments:

Post a Comment