如果您在 64 位环境中运行,我只会使用内存映射文件。进程没有(合理的)内存限制。你可以读入文件,甚至跳转,操作系统会在磁盘之间交换内存。
以下是一些基本信息:
http://msdn.microsoft.com/en-us/library/ms810613.aspx
这里是文件查看器的示例:
http://www.catch22.net/tuts/memory-techniques-part-1
这种情况适用于 x64 中的 2.8GB 文件,但在 win32 中失败,因为它不能为每个进程分配超过 2GB 的空间。它非常快,因为它只涉及 pBuf 数组中的第一个和最后一个字节。修改方法以遍历缓冲区并计算“零”字节的数量按预期工作。您可以看到内存占用量随着它的增加而增加,但该内存只是虚拟分配的。
#include "stdafx.h"
#include <string>
#include <Windows.h>
TCHAR szName[] = TEXT( pathToFile );
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hMapFile;
char* pBuf;
HANDLE file = CreateFile( szName, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if ( file == NULL )
{
_tprintf(TEXT("Could not open file object (%d).\n"),
GetLastError());
return 1;
}
unsigned int length = GetFileSize(file, 0);
printf( "Length = %u\n", length );
hMapFile = CreateFileMapping( file, 0, PAGE_READONLY, 0, 0, 0 );
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not create file mapping object (%d).\n"), GetLastError());
return 1;
}
pBuf = (char*) MapViewOfFile(hMapFile, FILE_MAP_READ, 0,0, length);
if (pBuf == NULL)
{
_tprintf(TEXT("Could not map view of file (%d).\n"), GetLastError());
CloseHandle(hMapFile);
return 1;
}
printf("First Byte: 0x%02x\n", pBuf[0] );
printf("Last Byte: 0x%02x\n", pBuf[length-1] );
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
return 0;
}