File Descriptor in C

Waqar Aslam Oct 12, 2023
  1. An Overview of File Descriptors
  2. File Descriptors in C Programming Language
  3. System Calls Using File Descriptor in C
File Descriptor in C

This article will discuss the file descriptor in the C programming language.

An Overview of File Descriptors

A file descriptor is a number that may be used to identify an open file in a computer’s operating system in a unique manner. It describes a data resource and the methods that may be used to access it.

File descriptors provide us with several methods, such as open, close, read, and write, to access files. A file descriptor is an integer number in its most basic form.

Each file that is opened receives its number. We call it a file descriptor.

A file descriptor is what is returned by the open() function after it has been used to open a file. Once that is done, we may utilize this file descriptor to carry out more actions on that file.

For instance, if we wish to read data from the opened file, we provide the file descriptor as input to the function that reads data.

File Table Entry: When a process requests to open a file, the file table entries are formed as a structure in memory that acts as a proxy for the open file. These entries are responsible for maintaining the file location.

File Descriptors in C Programming Language

Standard input (STDIN), standard output (STDOUT), and standard error (STDERR) are the first three file descriptors that are used by default on an operating system that is similar to Unix.

When any process begins, the file descriptors table for that process opens automatically with its fd (file descriptor) 0, 1, and 2 entries. Each of these three fd references an item in the file table for a file called /dev/tty.

Name File Descriptor Description
stdin 0 Standard input
stdout 1 Standard output
stderr 2 Standard error

System Calls Using File Descriptor in C

A system call is a method through which an operating system makes its services accessible to user applications via an application programming interface (API).

The following types of I/O system calls are utilized in this context.

open() Call Using File Descriptor

The name of the file that you wish to open is what is sent in as the first parameter to this method. After that, we offer some more options to determine the opening mode.

The return value will be set to -1 if it cannot open the file. Therefore, before we carry out any more activities on the opened file, we need to verify the value returned by the open() method.

If it has a value of -1, we know that the open() method could not open the file successfully.

Let us take an example to implement the open() call.

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[]) {
  int fileDescriptor;
  char buff[1000];

  if ((fileDescriptor = open("abc.txt", O_CREAT | O_RDONLY)) == -1) {
    printf("File Open Failed\n");
    exit(0);
  } else {
    printf("File Opened Successfully\n");
    printf("File Descriptor: %d\n", fileDescriptor);
  }
}

Output:

File Opened Successfully
File Descriptor: 3

An integer variable with the name fileDescriptor has been defined by us at the very beginning of the main function. This is to be used to store the value of the file descriptor.

After that, we used an if statement to test the value returned by the open function. If it is -1, we will terminate the application and show an error message.

If not, then we will be able to continue with the program. The string abc.txt is sent as the first input to the open function.

This is the actual name of the file that is being saved. Next, we have indicated that O_RDONLY should be used.

This indicates that we wish to open the file in read-only mode. Also, if the file does not exist, it should create the file using O_CREAT.

The following are some other arguments that we may utilize.

  1. O_WRONLY: This will open the file so that you can only write to it.
  2. O_RDWR: With this option, you may simultaneously open files to read and write to them.

close() Call Using File Descriptor

It is done so that access to the file system is terminated. When a program calls this system function, it indicates it no longer needs the file.

Consequently, the buffers are flushed, the file information is modified, and the resources associated with the file are de-allocated.

int close(int fd);

read() Call Using File Descriptor

The file descriptor is the first parameter that it accepts. As the argument, we will need to provide the descriptor used when the file was opened.

A pointer is sent in as the second parameter. The Read function will get the data from the specified file and store it where you have directed it.

As the value of this pointer, we may supply the address of the buffer area that was previously allocated. The third parameter specifies the number of bytes that should be read from the file.

The number of bytes that were successfully read from this file is returned by this file if the file was successfully read. It will return the value -1 if it does not succeed.

Syntax:

ssize_t read(int fd, void *buf, size_t count);

An example of reading a file using a file descriptor is as follows:

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[]) {
  int fileDescriptor;
  char buff[1000];

  if ((fileDescriptor = open("abc.txt", O_RDONLY)) == -1) {
    printf("File Opening Failed\n");
    exit(0);
  } else {
    printf("File Opened Successfully\n");
    printf("File Descriptor: %d\n", fileDescriptor);

    if (read(fileDescriptor, buff, sizeof(buff)) == -1) {
      printf("Error while reading file\n");
      exit(0);
    } else {
      printf("Text of the File: %s\n", buff);
    }
  }
  return 0;
}

Output:

File Opened Successfully
File Descriptor: 3
Text of the File: DelftStack has the solutions to all the programming-related problems
Author: Waqar Aslam
Waqar Aslam avatar Waqar Aslam avatar

I am Waqar having 5+ years of software engineering experience. I have been in the industry as a javascript web and mobile developer for 3 years working with multiple frameworks such as nodejs, react js, react native, Ionic, and angular js. After which I Switched to flutter mobile development. I have 2 years of experience building android and ios apps with flutter. For the backend, I have experience with rest APIs, Aws, and firebase. I have also written articles related to problem-solving and best practices in C, C++, Javascript, C#, and power shell.

LinkedIn

Related Article - C File