C program using the I/O system calls of UNIX/LINUX

Subject: OS (Operating Systems)

Contributed By: Nunugoppula Ajay

Created At: March 6, 2025

Question:


Write a C program using the I/O system calls of UNIX/LINUX operating system (open, read, write, close, fcntl, seek)?

Explanation Video:

Custom Image

Explanation:

 

Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define FILENAME "sample.txt"
#define BUFFER_SIZE 100

int main() {
    int fd;  
    char buffer[BUFFER_SIZE];

    // 1️⃣ OPEN / CREATE A FILE
    fd = open(FILENAME, O_CREAT | O_RDWR, 0644);
    if (fd == -1) {
        perror("Error opening/creating file");
        exit(1);
    }
    printf("File opened successfully with file descriptor: %d\n", fd);

    // 2️⃣ WRITE TO FILE
    char *data = "Hello, this is a UNIX system call example.\n";
    ssize_t bytes_written = write(fd, data, strlen(data));
    if (bytes_written == -1) {
        perror("Error writing to file");
        close(fd);
        exit(1);
    }
    printf("Data written successfully (%ld bytes)\n", bytes_written);

    // 3️⃣ SEEK TO BEGINNING
    if (lseek(fd, 0, SEEK_SET) == -1) {
        perror("Error using lseek");
        close(fd);
        exit(1);
    }
    printf("File pointer reset to the beginning using lseek()\n");

    // 4️⃣ READ FROM FILE
    ssize_t bytes_read = read(fd, buffer, BUFFER_SIZE - 1);
    if (bytes_read == -1) {
        perror("Error reading file");
        close(fd);
        exit(1);
    }
    buffer[bytes_read] = '\0';  // Null terminate the string
    printf("Data read from file:\n%s\n", buffer);

    // 5️⃣ FILE CONTROL OPERATION (fcntl)
    int flags = fcntl(fd, F_GETFL);
    if (flags == -1) {
        perror("Error getting file status flags");
        close(fd);
        exit(1);
    }
    printf("File descriptor flags: %d\n", flags);

    // 6️⃣ CLOSE THE FILE
    if (close(fd) == -1) {
        perror("Error closing file");
        exit(1);
    }
    printf("File closed successfully\n");

    return 0;
}
Output:
File opened successfully with file descriptor: 3
Data written successfully (40 bytes)
File pointer reset to the beginning using lseek()
Data read from file:
Hello, this is a UNIX system call example.
File descriptor flags: 2
File closed successfully
Share this Article & Support Us:
Status
printf('Loading...');