Implementation of quick file reading using memory mapping in C++.
In C++, the CreateFileMapping function can be used to create a file mapping object to map a file into the virtual address space of a process. Subsequently, the MapViewOfFile function can be used to map the file into memory, enabling fast file reading operations.
Here is an example code demonstrating how to quickly read a file using memory mapping.
#include <iostream>
#include <Windows.h>
int main() {
HANDLE hFile = CreateFile(L"example.txt", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
std::cout << "Failed to open file." << std::endl;
return 1;
}
HANDLE hMapFile = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
if (hMapFile == NULL) {
std::cout << "Failed to create file mapping." << std::endl;
CloseHandle(hFile);
return 1;
}
LPVOID pData = MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 0);
if (pData == NULL) {
std::cout << "Failed to map view of file." << std::endl;
CloseHandle(hMapFile);
CloseHandle(hFile);
return 1;
}
// 读取文件内容
char* pFileData = static_cast<char*>(pData);
std::cout << "File content: " << pFileData << std::endl;
UnmapViewOfFile(pData);
CloseHandle(hMapFile);
CloseHandle(hFile);
return 0;
}
In the example above, the file example.txt is first opened using the CreateFile function. Then, a file mapping object hMapFile is created using the CreateFileMapping function. Next, the file is mapped into memory with the MapViewOfFile function, returning a pointer to the file content pData. Finally, by casting pData to type char*, we can access and manipulate the file content.
It is important to note that after using file mapping, you need to call the UnmapViewOfFile function and CloseHandle function to release resources.
The method of quickly reading files using the CreateFileMapping function in C++ has been described. When dealing with larger files, memory mapping can offer more efficient reading performance.