Load binary file into buffer in Windows (C++/MFC)



Following is the function to load a binary file into a memory buffer in Windows (C++/MFC).

 
 
//Do not use this for text files as the following code doesn't handle UTF, UNICODE, BOMLESS etc.
BOOL LoadFromBinaryFile(CString strFilePath, BYTE **pBuf, DWORD *pSize)
{
 
	HANDLE hFile = NULL;
	BOOL bRet;
 
	try
	{
		DWORD dwFileSize = 0, dwRead = 0, dwTotalRead = 0;
 
		hFile = CreateFile(strFilePath
		,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING
		,FILE_ATTRIBUTE_NORMAL,NULL);
 
		if (hFile == INVALID_HANDLE_VALUE)
		{
			throw -1;
		}else
		{
			dwFileSize = ::GetFileSize(hFile,NULL);
			if (dwFileSize == 0 )
			{
				*pSize = 0;
				*pBuf = NULL;
			}else
			{
 
				*pBuf = new BYTE[dwFileSize];
				dwRead = 0;
				// the file size.. does not include NULL character
				*pSize = dwFileSize;
 
				do
				{
					dwRead = 0;
					bRet = ReadFile(hFile,(LPVOID)(*pBuf+dwTotalRead)
						,dwFileSize-dwTotalRead,&dwRead,NULL);
 
					dwTotalRead += dwRead;
 
					if (bRet == 0)
					{
						delete *pBuf;
						*pBuf = NULL;
						throw -1;
 
					}
 
				}while( (dwTotalRead != dwFileSize) );
 
			}
 
			CloseHandle(hFile);
 
		}
 
	}catch(int iErr)
	{
		// just assigned to avoid warning of unreferenced local variable
		iErr = -1;
		CloseHandle(hFile);
		return FALSE;
	}
 
	return TRUE;
 
}


Leave a Reply

Your email address will not be published. Required fields are marked *