内存映射文件

本文介绍了一种方法来遍历大型文件并计算其中0字节的数量。通过使用Windows API函数,如GetSystemInfo、CreateFile、CreateFileMapping、GetFileSize及MapViewOfFile等,程序能够有效地处理大型文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 __int64 Count0s(void) {
 //Views must always start on a multiple
 //of the allocation granularity
 SYSTEM_INFO sinf;
 GetSystemInfo(&sinf);
 //Open the data file.
 HANDLE hFile = CreateFile(L"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);
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值