Reading and Writing

To read from a file view, a process dereferences the pointer returned by the MapViewOfFile function:

DWORD dwLength;

dwLength = *((LPDWORD) lpMapAddress);
 

The process also uses the pointer returned by MapViewOfFile to write to the file view:

*((LPDWORD) lpMapAddress) = dwLength;
 

The FlushViewOfFile function copies the specified number of bytes of the file view to the physical file, without waiting for the cached write operation to occur:

if (!FlushViewOfFile(lpMapAddress, dwBytesToFlush)) 
{ 
    ErrorHandler("Could not flush memory to disk."); 
} 
 

Note  Reading from or writing to a file view can cause an exception. For example, accessing a mapped file that resides on a remote server can generate an exception if the connection to the server is lost. Exceptions can also occur because of a full disk, because the file is shared and a different process has locked a byte range, or because of an underlying device failure or memory allocation failure. To guard against access violations, all accesses to memory mapped files should be wrapped in structured exception handlers.

If you are mapping a compressed or sparse file on an NTFS partition, there is additional potential for an access violation. In this case, the address space mapped by MapViewOfFile may not be backed by allocated disk space. This is because a sparse file can have regions of zeroes for which NTFS does not allocate disk space, and a compressed file can take up less disk space than the actual data that it represents. If you read from or write to a portion of a sparse or compressed file that is not backed by disk space, the system may try to allocate disk space. If the disk is full, this can result in an access violation.

For more information, see File Compression, Sparse Files, and Structured Exception Handling.