Linux System Programming: File Read and Write

Click on the above “Mechanical and Electronic Engineering Technology” to follow us

1. API

In Linux system programming, file read and write involve a series of standard POSIX APIs. Here are some commonly used file operation-related APIs and their detailed descriptions:

open() Function

The open() function is used to open a file and returns a file descriptor for subsequent read and write operations.

Prototype:

int open(const char *pathname, int flags, ...);

Parameters:

  • pathname: The path of the file to be opened.

  • flags: The mode and options for opening the file, which can be a combination of the following flags:

    • O_RDONLY: Open the file in read-only mode.

    • O_WRONLY: Open the file in write-only mode.

    • O_RDWR: Open the file in read-write mode.

    • O_CREAT: Create a new file if it does not exist.

    • O_TRUNC: If the file exists, truncate its length to 0.

    • O_APPEND: Append data to the end of the file when writing.

  • mode (optional): When the O_CREAT flag is set, this parameter specifies the permission mode of the file.

Return value: Returns a non-negative file descriptor on success; returns -1 and sets errno to indicate an error on failure. read() Function

read() Function

Used to read data from a file descriptor.

Prototype:

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

Parameters:

  • fd: File descriptor.

  • buf: Pointer to the buffer for storing the read data.

  • count: The number of bytes to read.

Return value: Returns the number of bytes read on success; returns 0 if the end of the file is reached; returns -1 and sets errno on failure.

write() Function

The write() function is used to write data to a file descriptor.

Prototype:

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

Parameters:

  • fd: File descriptor.

  • buf: Pointer to the buffer containing the data to be written.

  • count: The number of bytes to write.

Return value: Returns the number of bytes written on success; returns -1 and sets errno on failure.

close() Function

The close() function is used to close a file descriptor.

Prototype:

int close(int fd);

Parameters:

  • fd: The file descriptor to be closed.

Return value: Returns 0 on success; returns -1 and sets errno on failure.

lseek() Function

The lseek() function is used to reposition the read/write location of a file descriptor.

Prototype:

off_t lseek(int fd, off_t offset, int whence);

Parameters:

  • fd: File descriptor.

  • offset: The displacement relative to whence.

  • whence: The starting position for addressing, which can be one of the following values:

    • SEEK_SET: Beginning of the file.

    • SEEK_CUR: Current position.

    • SEEK_END: End of the file.

Return value: Returns the new file position (byte offset) on success; returns (off_t)-1 and sets errno on failure.

Error Handling

When these functions fail, errno is usually set to indicate the specific error. errno is a global variable that contains the error code. You can use perror() or strerror() to print or get the error description.

Example:

if (read(fd, buf, sizeof(buf)) == -1) {
    perror("Read error");
    // or
    fprintf(stderr, "Read error: %s\n", strerror(errno));
}
These APIs are the basic tools for handling files in Linux system programming. Mastering them is crucial for developing Linux applications that require file interaction.
2. Operation Examples

Basic Steps for File Read and Write

  • Open File: Use the open() function to open a file.

  • Read and Write File: Use the read() and write() functions for file read and write operations.

  • Close File: Use the close() function to close the file.

Open File

#include <fcntl.h> // Include open() function
#include <unistd.h> // Include close() and read() functions
#include <stdio.h>  // Include perror() and printf() functions

int main() {
    int fd;
    fd = open("example.txt", O_RDWR | O_CREAT, 0666);
    if (fd == -1) {
        perror("Error opening file");
        return -1;
    }
    // File opened successfully, fd is the file descriptor
    return 0;
}

Read and Write File

#include <string.h> // Include string for writing data

// Write to file
char *text = "Hello, World!\n";
write(fd, text, strlen(text));

// Read from file
char buffer[1024];
int bytes_read = read(fd, buffer, sizeof(buffer));
if (bytes_read == -1) {
    perror("Error reading from file");
} else {
    printf("Read %d bytes: %s", bytes_read, buffer);
}

Close File

if (close(fd) == -1) {
    perror("Error closing file");
    return -1;
}

Complete Example

#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>

int main() {
    int fd;
    char *text = "Hello, World!\n";
    char buffer[1024];

    // Open file
    fd = open("example.txt", O_RDWR | O_CREAT, 0666);
    if (fd == -1) {
        perror("Error opening file");
        return -1;
    }

    // Write to file
    if (write(fd, text, strlen(text)) == -1) {
        perror("Error writing to file");
        return -1;
    }

    // Read from file
    lseek(fd, 0, SEEK_SET); // Move file pointer to the beginning of the file
    int bytes_read = read(fd, buffer, sizeof(buffer));
    if (bytes_read == -1) {
        perror("Error reading from file");
    } else {
        printf("Read %d bytes: %s", bytes_read, buffer);
    }

    // Close file
    if (close(fd) == -1) {
        perror("Error closing file");
        return -1;
    }

    return 0;
}

Notes

  • The file descriptor fd is the integer value used to identify the file after it is opened.

  • O_RDWR indicates opening the file in read-write mode, O_CREAT indicates creating the file if it does not exist.

  • 0666 is the permission mode for the file, indicating that the file owner, group, and other users have read and write permissions.

  • Using the lseek() function allows moving the file pointer to any position in the file.

  • Always check the return value of system calls to determine if the operation was successful.

  • It is very important to use the close() function to close the file after reading and writing to release system resources.

These basic operations are the foundation of file handling in Linux system programming. Mastering these operations is crucial for developing Linux applications that require file interaction.
Linux System Programming: File Read and Write

Want to know more

Scan the code to follow

Leave a Comment