Implement fast file reading using memory mapping in C++ CreateFileMapping.
In C++, one can create a memory mapping of a file using the CreateFileMapping function, and then map the file to memory using MapViewOfFile function to easily read the file by accessing the memory.
Below is a sample code demonstrating how to use the CreateFileMapping and MapViewOfFile functions to achieve fast file reading:
#include <iostream>
#include <windows.h>
int main() {
// 打开文件
HANDLE fileHandle = CreateFile("test.txt", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (fileHandle == INVALID_HANDLE_VALUE) {
std::cout << "Failed to open file" << std::endl;
return 1;
}
// 获取文件大小
DWORD fileSize = GetFileSize(fileHandle, NULL);
// 创建文件映射
HANDLE mappingHandle = CreateFileMapping(fileHandle, NULL, PAGE_READONLY, 0, 0, NULL);
if (mappingHandle == NULL) {
std::cout << "Failed to create file mapping" << std::endl;
CloseHandle(fileHandle);
return 1;
}
// 映射文件到内存
LPVOID fileMapping = MapViewOfFile(mappingHandle, FILE_MAP_READ, 0, 0, fileSize);
if (fileMapping == NULL) {
std::cout << "Failed to map view of file" << std::endl;
CloseHandle(mappingHandle);
CloseHandle(fileHandle);
return 1;
}
// 读取文件内容
char* fileData = static_cast<char*>(fileMapping);
for (DWORD i = 0; i < fileSize; i++) {
std::cout << fileData[i];
}
// 关闭映射和文件句柄
UnmapViewOfFile(fileMapping);
CloseHandle(mappingHandle);
CloseHandle(fileHandle);
return 0;
}
In this example, the file is first opened using the CreateFile function to obtain its size. Next, a file mapping object is created with the CreateFileMapping function and the file is mapped into memory using MapViewOfFile. Finally, the file contents are quickly read by accessing the memory.
Please remember to release resources by calling functions like UnmapViewOfFile and CloseHandle after use.