Memory-Mapped File Operations in C Language

Memory-Mapped File Operations in C Language

A memory-mapped file is a technique that maps the contents of a file directly into the process’s address space. This allows the program to access file data as if it were accessing memory, thereby improving I/O efficiency. In C language, we can use the mmap function to perform memory-mapped file operations. This article will detail how to use memory-mapped files in C and provide example code.

1. Basic Concepts of Memory Mapping

In traditional file I/O operations, the program needs to read or write data through system calls (such as read and write), which involves multiple context switches. However, with memory mapping, the entire file is loaded into the process’s virtual address space, allowing the program to access this data directly through pointers. This method not only simplifies the code but also enhances performance.

2. Using mmap

2.1 Function Prototype

void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
  • addr: The starting address of the mapping area, generally set to NULL, allowing the system to choose automatically.
  • length: The number of bytes to be mapped.
  • prot: The protection flags for the mapping area, which can be a combination of the following values:
    • PROT_READ: Readable
    • PROT_WRITE: Writable
    • PROT_EXEC: Executable
  • flags: Mapping options, which can be one of the following values or a combination:
    • MAP_SHARED: All processes share this area
    • MAP_PRIVATE: Private copy, does not affect other processes
  • fd: File descriptor obtained through open().
  • offset: The position offset from the beginning of the file.

2.2 Example Code

Below is a simple example demonstrating how to create a text file and read its contents using memory mapping.

Creating and Writing to a Text File

First, we create a text file named “example.txt” and write some content into it:

#include <stdio.h>
int main() {
    FILE *file = fopen("example.txt", "w");
    if (file == NULL) {
        perror("Failed to open file");
        return -1;
    }
    fprintf(file, "Hello, Memory Mapped Files!\n");
    fclose(file);
    return 0;
}

Reading Text Content Using Memory Mapping

Next, we write another program to read the text content through memory mapping:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
int main() {
    // Open the file to be memory-mapped
    int fd = open("example.txt", O_RDONLY);
    if (fd == -1) {
        perror("Failed to open file");
        return EXIT_FAILURE;
    }
    // Get the file size
    off_t filesize = lseek(fd, 0, SEEK_END);
    // Memory map the file
    char *mapped = mmap(NULL, filesize, PROT_READ, MAP_SHARED, fd, 0);
    if (mapped == MAP_FAILED) {
        perror("Failed to map the file");
        close(fd);
        return EXIT_FAILURE;
    }
    // Output the data read from mapped
    printf("%s", mapped);
    // Clean up resources
    munmap(mapped, filesize);
    close(fd);
    return EXIT_SUCCESS;
}

Program Explanation

  1. Opening and Getting Size: We first open “example.txt” and get its size so that we know how many bytes to map.

  2. Calling mmap: We use the mmap() function to load the entire text content into our process’s address space. Here we set the protection flag to read-only since we only want to read the data.

  3. Outputting Results: We directly print the data obtained from the mapped area, just like handling a regular string.

  4. Cleaning Up Resources: Finally, we use munmap() to release the allocated virtual address space and close the opened file descriptor.

Conclusion

This article introduced the basic memory mapping operations in C language, including how to create, open, and read/write using the mmap() function. Compared to traditional I/O methods, utilizing memory mapping can significantly enhance performance while also making the code simpler and more understandable. In practical applications, this technique is often used in scenarios such as large-scale data processing and efficient caching. We hope this article helps you better understand and utilize the memory mapping capabilities in C language.

Leave a Comment