1.3.11 Mapped Files

Win32 provides functions that allow an application to map files into the address space of a process. Data within the file can then be accessed using memory read/write instructions rather than I/O system functions such as ReadFile and WriteFile.

The functions are best suited to applications that need to read a file and parse the information contained within the file. This includes editors that map and parse the input file, compilers that map and parse source files, spreadsheets that map and parse the input spreadsheet . . . Mapping a file to read and parse the file allows an application to manipulate the file using memory operations rather than having to do reads and writes and seeks all over the file. Operations such as “unreading” a character are much easier to do with mapped files. All the application has to do is decrement a pointer. Doing this operation with regular reads and writes requires a much more complicated approach usually requiring an application to write its own buffering layer.

Another application for mapped files is to use them to support persistent named shared memory. An application could create a file, map it, then others could use this as shared memory by opening and mapping the file.

While file mapping can be used to write into memory causing a data file to be written, this is a more complicated use of file mapping and is not as easy to use.

Mapping a file occurs in two stages:

The potential for mapping a section of the file is created by creating a file mapping object.

A view of the mapping object may be mapped into the address space of the process allowing data in the file to be manipulated.

For more information on file mapping, see the Memory Overview.

The file mapping functions include:

Function Description

CreateFileMapping Creates a file mapping object.
FlushViewOfFile Flushes a mapped file to disk.
MapViewOfFile Maps part of a file into memory.
OpenFileMapping Opens a file for mapping.
UnmapViewOfFile Unmaps a file.