您的位置:首页 > 其它

Windows平台大文件的访问

2009-03-12 16:37 441 查看
以下为 Windows 核心编程的示例

计算一个二进制数据文件中的所有0字节的数目,文件大小可以超过4GB。

__int64 Count0s()
{
//Views must always start on a multiple
//of the allocation granularity
SYSTEM_INFO sinf;
GetSystemInfo(&sinf);

//Open the data file.
HANDLE hFile = CreateFile("C://HugeFile.Big", GENERIC_READ,
FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);

//Create the file-mapping object.
HANDLE hFileMapping = CreateFileMapping(hFile, NULL,
PAGE_READONLY, 0, 0, NULL);

DWORD dwFileSizeHigh;
__int64 qwFileSize = GetFileSize(hFile, &dwFileSizeHigh);
qwFileSize += (((__int64) dwFileSizeHigh) << 32);

//We no longer need access to the file object's handle.
CloseHandle(hFile);

__int64 qwFileOffset = 0, qwNumOf0s = 0;

while (qwFileSize > 0)
{
// Determine the number of bytes to be mapped in this view
DWORD dwBytesInBlock = sinf.dwAllocationGranularity;

if(qwFileSize < sinf.dwAllocationGranularity)
dwBytesInBlock =(DWORD) qwFileSize;

PBYTE pbFile = (PBYTE) MapViewOfFile(hFileMapping, FILE_MAP_READ,
(DWORD)(qwFileOffset >> 32), // Starting byte
(DWORD)(qwFileOffset & 0xFFFFFFFF), // in file
dwBytesInBlock); // # of bytes to map

// Count the number of Js in this block.
for(DWORD dwByte = 0; dwByte < dwBytesInBlock; dwByte++)
{
if(pbFile[dwByte] == 0)
qwNumOf0s++;
}

// Unmap the view; we don't want multiple views
// in our address space.
UnmapViewOfFile(pbFile);

// Skip to the next set of bytes in the file.
qwFileOffset += dwBytesInBlock;
qwFileSize -= dwBytesInBlock;
}

CloseHandle(hFileMapping);
return(qwNumOf0s);
}

这个算法用于映射64 KB(分配粒度的大小)或更小的视图。另外,要记住,MapViewOfFile 函数要求文件的位移是分配粒度大小的倍数。当每个视图被映射到地址空间时,对0的扫描不断进行。当每个64 KB的文件块已经映射和扫描完毕时,就要通过关闭文件映射对象来对每个文件块进行整理。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: