File Mapping in C++ Applications
Last Updated :
13 Apr, 2021
File mapping is a concept where a file map object can be created for a file on the disk. Thereafter, different processes can create a view of this file mapping object in their virtual address spaces. A process can create one or more views of the file mapping object in its virtual address space and work on it. Below is the working diagram for the file mapping object:
Do remember the following key points
- The file is present on the disk of the machine on which the processes are running.
- The file mapping object is present in the physical memory.
- More than one process can create views for the same file mapping object.
- The file mapping object can contain the entire file or a part of it. Similarly, the file view for processes can contain the entire file mapping object or a part of it.
- All the copies are coherent and the same as that present on the disk.
Advantages
- It is a great help when working with huge files like database files as not the whole file needs to be present in the physical memory.
- More than one process can use a file on the disk for both read and write operations. Each process can create a new view, un-mapping the current file view.
Steps to create a file mapping object and file view
Step 1: Create or open a file object that represents the file on the disk. Here, we created a new file object with handle as hFile and named as "datafile.txt".
HANDLE CreateFileA(
LPCSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
);
// Can be used as
HANDLE hFile = CreateFile(TEXT("datafile.txt"),
GENERIC_READ | GENERIC_WRITE,
0,
// Open with exclusive access
NULL,
// No security attributes
// Creating a new temp file
CREATE_NEW,
// Delete the file after unmapping the view
FILE_FLAG_DELETE_ON_CLOSE,
NULL);
HANDLE CreateFileA(
LPCSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
);
// Can be used as
HANDLE hFile = CreateFile(TEXT("datafile.txt"),
GENERIC_READ | GENERIC_WRITE,
0, // open with exclusive access
NULL, // no security attributes
CREATE_NEW, // creating a new temp file
FILE_FLAG_DELETE_ON_CLOSE, //delete the file after unmapping the view
NULL);
Step 2: Create a map object for the file that contains information about how to access the file and its size. So, after creating the above file we use its handle and create its mapping in the physical memory.
HANDLE CreateFileMappingA(
HANDLE hFile,
LPSECURITY_ATTRIBUTES lpFileMappingAttributes,
DWORD flProtect,
DWORD dwMaximumSizeHigh,
DWORD dwMaximumSizeLow,
LPCSTR lpName
);
// Can be used as
HANDLE hFileMapping = ::CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, bufferSize, filename);
Step 3: Map all or part of the file-mapping object from the physical memory into your process's virtual address space. So here we are creating the view of the mapped file which will be used by the process.
LPVOID MapViewOfFile(
HANDLE hFileMappingObject,
DWORD dwDesiredAccess,
DWORD dwFileOffsetHigh,
DWORD dwFileOffsetLow,
SIZE_T dwNumberOfBytesToMap
);
// Can be used as
void* p = ::MapViewOfFile(hFileMapping, FILE_MAP_ALL_ACCESS, 0, param1, param2);
Step 4: Cleaning up
4(A) Un-map the file mapping object from the process address space. Backtrack the above steps and firstly, remove the file views from the process's address space.
BOOL UnmapViewOfFile(LPCVOID lpBaseAddress
);
// Can be used as
UnmapViewOfFile(p);
4(B) Close the file mapping object. This step removes the file mapping from physical memory.
CloseHandle(hFileMapping);
4(C) Close the file object. Here, close the file opened on the disk and free the handle. Since in the first step we set flag FILE_FLAG_DELETE_ON_CLOSE, the file will be deleted after this step.
CloseHandle(hFile);
Note:
- Close the handles in the same order or else it will give rise to discrepancies.
- Close all the open file handles before trying to delete the file.
Similar Reads
MakeFile in C++ and its applications
In C++, building a simple program is easy with the help of CLI of the compiler. But it becomes progressively difficult to maintain and build the project when its size increases. We may need to write multiple lines of commands just to simply compile it. This can be simplified by using Makefile for th
5 min read
C++ File Writer-Reader application using Windows Threads
In this article, we will create a simple Writer-Reader application, which uses two threads, one for Writing into the file and another for Reading from the file. Here we will discuss the approach using Win32 Threads in C/C++. A windows thread can be created using the CreateThread() method. Approach:
3 min read
How to Open and Close a File in C++?
In C++, we can open a file to perform read and write operations and close it when we are done. This is done with the help of fstream objects that create a stream to the file for input and output. In this article, we will learn how to open and close a file in C++. Open and Close a File in C++ The fst
2 min read
C++ Program to Append a String in an Existing File
Here, we will build a C++ program to append a string in an existing file using 2 approaches i.e. Using ofstreamUsing fstreamC++ programming language offers a library called fstream consisting of different kinds of classes to handle the files while working on them. The classes present in fstream are
2 min read
CSV File Management Using C++
CSV is a simple file format used to store tabular data such as a spreadsheet or a database. CSV stands for Comma Separated Values. The data fields in a CSV file are separated/delimited by a comma (â, â) and the individual rows are separated by a newline (â\nâ). CSV File management in C++ is similar
7 min read
Implementation of file allocation methods using vectors
Prerequisite: File Allocation Methods Different File Allocation methods: 1. Contiguous File Allocation Methods: This is a type of allocation in which a file occupies contiguous blocks of a given memory. This type of allocation is fastest because we can access any part of the file just by adding it t
15+ min read
Contact Book in C++ using File Handling
Straightaway prior brushing up knowledge of the language and file handling is required. So let us do discuss C++ Language concepts in File Handling and loops. Straight we know that for compiling the code, an IDE for compiling C++ language is required such as Code Block, Visual Studio Code, Dev C++,
4 min read
Code Bloating in C++ with Examples
Code bloat is the production of code that is perceived as unnecessarily long, slow, or otherwise wasteful of resources. It is a problem in Software Development which makes the length of the code of software long unnecessarily. So for writing the quality code, we always avoid code bloating in our pro
3 min read
How Can I Get a File Size in C++?
In C++, we often need to determine the size of a file which is the number of bytes in a file. This is done for various applications, such as file processing or validation. In this article, we will learn how to get the file size in C++. Example: Input: FilePath = "C:/Users/Desktop/myFile.txt" Output:
2 min read
How to Read a File Using ifstream in C++?
In C++, we can read the contents of the file by using the ifstream object to that file. ifstream stands for input file stream which is a class that provides the facility to create an input from to some particular file. In this article, we will learn how to read a file line by line through the ifstre
2 min read