Skip to content

Instantly share code, notes, and snippets.

@plowsec
Created May 26, 2020 12:07
Show Gist options
  • Save plowsec/6f7db6a59258863f856088fd0079d63a to your computer and use it in GitHub Desktop.
Save plowsec/6f7db6a59258863f856088fd0079d63a to your computer and use it in GitHub Desktop.
Read a file with the Win32 API
void read_file(char* path, PBYTE buffer, size_t bufsize, DWORD* size_read) {
HANDLE hFile;
hFile = CreateFileA(path, // file to open
GENERIC_READ, // open for reading
FILE_SHARE_READ, // share for reading
NULL, // default security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
if (hFile == INVALID_HANDLE_VALUE) {
std::cout << "Terminal failure: unable to open file for reading" << std::endl;
return;
}
DWORD file_size = 0;
file_size = GetFileSize(hFile, NULL);
if (file_size > bufsize) {
std::cout << ("Not big enough, abort.\n");
return;
}
DWORD dw_read = 0;
if (FALSE == ReadFile(hFile, buffer, file_size, &dw_read, NULL))
{
std::cout << ("Terminal failure: Unable to read from file.\n GetLastError=%08x\n", GetLastError());
CloseHandle(hFile);
return;
}
if (dw_read == 0)
{
std::cout << ("No data read from file\n");
}
*size_read = dw_read;
CloseHandle(hFile);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment