C++ || Snippet – How To Use Memory Mapped Files

Print Friendly, PDF & Email

The following is sample code which demonstrates the use of the “mmap”, “munmap” and “getpagesize” function calls on Unix based systems.

A memory mapped file is a segment of virtual memory which has been assigned a direct byte for byte correlation with some portion of a file or file like resource. This resource is typically a file that is physically present on disk, but can also be a device, shared memory object, or other resource that the operating system can reference through a file descriptor.

The primary benefit of memory mapping a file is increasing I/O performance, especially when used on large files. Accessing memory mapped files is faster than using direct read and write operations for two reasons. Firstly, a system call is orders of magnitude slower than a simple change to a program’s local memory. Secondly, in most operating systems the memory region mapped actually is the kernel’s page cache (file cache), meaning that no copies need to be created in user space.

The following example demonstrates the use of the “mmap” to map a file into memory, and display its contents to the screen.

The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

The following is sample output:

./mmap mmap.cpp


Was this article helpful?
👍 YesNo

Leave a Reply