C++大數據的讀寫

當一個文件1G以上的這種,使用內存文件映射會提升讀寫效率;編程

下邊時段出自《windows核心編程》,讀取一個大文件,而後統計裏邊字符出現次數的函數:windows

__int64 CountOs(void)
{
    // Get system granularity
    SYSTEM_INFO sinf;
    GetSystemInfo(&sinf);

    // open the data file
    HANDLE hFile = CreateFile(TEXT("C:\\1.TXT"), 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 dwFileSizeHight;
    __int64 qwFileSize = GetFileSize(hFile, &dwFileSizeHight);
    qwFileSize += (((__int64)dwFileSizeHight) << 32);

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

    __int64 qwFileOffset = 0, qwNumOf0s = 0;

    while (qwFileSize > 0)
    {
        DWORD dwBytesInBlock = sinf.dwAllocationGranularity;
        if (qwFileSize < sinf.dwAllocationGranularity)
            dwBytesInBlock = (DWORD)qwFileSize;
        PBYTE pbFile = (PBYTE)MapViewOfFile(hFileMapping, FILE_MAP_READ, (DWORD)(qwFileOffset >> 32), (DWORD)(qwFileOffset & 0xFFFFFFFF), dwBytesInBlock);

        // count the number of 0s in this block.
        for (DWORD dwByte = 0; dwByte < dwBytesInBlock; dwByte++)
        {
            if (pbFile[dwByte] == 'r')
                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;
}
若是是往裏邊寫數據就用 memcpy把數據考入pbFile指向的內存。還有就是把讀標誌該成寫標誌; 
相關文章
相關標籤/搜索