Thread: Reading a File - FASTEST WAY POSSIBLE??

  1. #16
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    Code:
    #include <windows.h>
    #include <stdio.h>
    
    
    /*
     * Map a file for read access. Returns size of view in lpcbSize
     */
    LPVOID MapFileRead(LPCTSTR szFileName, size_t * lpcbSize)
    {
    	HANDLE hFile, hMapping;
    	DWORD  dwFileSize;
    	LPVOID lpView;
    	MEMORY_BASIC_INFORMATION mbi;
    
    	*lpcbSize = 0;
    
    	hFile = CreateFile(szFileName, GENERIC_READ, FILE_SHARE_READ, NULL,
    	                   OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    	if (INVALID_HANDLE_VALUE == hFile)
    	{
    		return NULL;
    	}
    
    	dwFileSize = GetFileSize(hFile, NULL);
    	if (INVALID_FILE_SIZE == dwFileSize)
    	{
    		CloseHandle(hFile);
    		return NULL;
    	}
    
    	hMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
    	if (NULL == hMapping)
    	{
    		CloseHandle(hFile);
    		return NULL;
    	}
    
    	lpView = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
    
    	CloseHandle(hMapping);
    	CloseHandle(hFile);
    
    	if (NULL != lpView)
    	{
    		if (VirtualQuery(lpView, &mbi, sizeof(mbi)) >= sizeof(mbi))
    		{
    			*lpcbSize = min(dwFileSize, mbi.RegionSize);
    		}
    		else
    		{
    			*lpcbSize = dwFileSize;
    		}
    	}
    
    	return lpView;
    }
    
    
    /*
     * Close a file mapping view.
     */
    BOOL MapFileClose(LPCVOID lpView)
    {
    	return UnmapViewOfFile(lpView);
    }
    
    
    int main(void)
    {
    	size_t cbSize, i;
    	const char * file_view;
    
    	file_view = (const char *) MapFileRead(TEXT("File Mapping2.cpp"), &cbSize);
    
    	if (file_view)
    	{
    		try
    		{
    			for (i = 0;i < cbSize; i++)
    			{
    				printf("%c", file_view[i]);
    			}
    		}
    		catch (...)
    		{
    			printf("Oh oh, not good doctor.");
    		}
    
    		MapFileClose(file_view);
    	}
    
    	getchar();
    	return 0;
    }
    It is strongly recommended that you wrap code that uses a file view in exception handling. This is in case the backing file becomes unavailable, such as a network cable unplugged, etc.
    Last edited by anonytmouse; 06-19-2004 at 03:51 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sequential file program
    By needhelpbad in forum C Programming
    Replies: 80
    Last Post: 06-08-2008, 01:04 PM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  4. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM