Created
January 20, 2024 19:38
-
-
Save MurylloEx/614b601228c6f6db019b264830667da8 to your computer and use it in GitHub Desktop.
Load an arbitrary file to memory using a combination of CreateFileW + ReadFile + HeapAlloc + HeapFree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
BOOL GetFileBufferInMemory( | |
LPCWSTR lpFileName, | |
LPVOID* pDestBuffer | |
) { | |
HANDLE FileHandle = CreateFileW(lpFileName, GENERIC_READ, NULL, NULL, OPEN_EXISTING, NULL, NULL); | |
if (FileHandle == INVALID_HANDLE_VALUE) { | |
printf_s("CreateFileW failed to retrieve the file handle."); | |
return FALSE; | |
} | |
DWORD FileSize = GetFileSize(FileHandle, NULL); | |
if (FileSize == INVALID_FILE_SIZE) { | |
printf_s("GetFileSize failed to retrieve the file size."); | |
return FALSE; | |
} | |
LPVOID pBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, FileSize); | |
if (pBuffer == NULL) { | |
printf_s("HeapAlloc failed to allocate in-memory page block."); | |
return FALSE; | |
} | |
DWORD TotalReadBytes = 0; | |
BOOL Status = ReadFile(FileHandle, pBuffer, FileSize, &TotalReadBytes, NULL); | |
if ((Status == FALSE) || (TotalReadBytes != FileSize)) { | |
HeapFree(GetProcessHeap(), NULL, pBuffer); | |
return FALSE; | |
} | |
*pDestBuffer = pBuffer; | |
return CloseHandle(FileHandle); | |
} | |
BOOL ReleaseFileBufferInMemory(LPVOID pDestBuffer) { | |
return HeapFree(GetProcessHeap(), NULL, pDestBuffer); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment