AI Features

Working Directly with System Calls

Learn to handle return values from system calls carefully, reliably detect errors, and manage data transfer with precise control.

Previously, we learned that file descriptors are integers used by the operating system to represent open files and other resources. We now move from understanding descriptors to using them directly. In this lesson, we explore the core system calls and learn how to check return values, handle errors properly, and perform unbuffered I/O for precise control over data transfer.

Opening a file with open()

The open() system call is declared in <fcntl.h> and is used to request access to a file from the operating system. Below is the basic syntax:

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

Let's see in practice below:

Opening a file using open() and checking for errors

To see the content in the data.txt file, type the cat data.txt command in the terminal above. In the above code:

  • Line 6: open() requests the kernel to open (or create) data.txt with these flags:

    • O_WRONLY → open for writing

    • O_CREAT → create the file if it does not exist

    • O_TRUNC → truncate ...