How do I use mmap for fast I/O in C++?

mmap is a powerful mechanism that allows you to map a file or device into memory. In C++, it can be used for fast I/O by providing direct access to the file's contents, enabling efficient reading and writing without the overhead of traditional I/O calls.

Using mmap for Fast I/O in C++

To use mmap in C++, follow these steps:

  1. Include necessary headers:
  2. #include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <iostream> #include <cstring>
  3. Open the file using open() to get the file descriptor.
  4. Use mmap() to map the file into memory.
  5. Access the data directly through the pointer returned by mmap().
  6. Don't forget to unmap the memory and close the file descriptor after usage.

Example Code

#include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <iostream> #include <cstring> int main() { const char *fileName = "example.txt"; int fd = open(fileName, O_RDWR); if (fd == -1) { std::cerr << "Error opening file." << std::endl; return 1; } size_t fileSize = lseek(fd, 0, SEEK_END); lseek(fd, 0, SEEK_SET); char *mapped = (char *)mmap(NULL, fileSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (mapped == MAP_FAILED) { std::cerr << "Error mapping file." << std::endl; close(fd); return 1; } // Perform read/write operations on the mapped memory std::cout << "File content: " << std::string(mapped, fileSize) << std::endl; strcpy(mapped, "New content written to file\n"); // Writes directly to file // Clean up munmap(mapped, fileSize); close(fd); return 0; }

mmap fast I/O C++ memory mapping file I/O performance optimization