Ali Sepehri-Amin
Ali Sepehri-Amin

Reputation: 493

Read 'Binary' files with ReadFile WinAPI

When I try to open '.exe' files with ReadFile() Windows API, It's just return the 2 first character of file like : MZ

Here is my Code:

#define BUFFERSIZE 5000

VOID CALLBACK FileIOCompletionRoutine(
__in  DWORD dwErrorCode,
__in  DWORD dwNumberOfBytesTransfered,
__in  LPOVERLAPPED lpOverlapped
);

VOID CALLBACK FileIOCompletionRoutine(
__in  DWORD dwErrorCode,
__in  DWORD dwNumberOfBytesTransfered,
__in  LPOVERLAPPED lpOverlapped)
{
   _tprintf(TEXT("Error code:\t%x\n"), dwErrorCode);
   _tprintf(TEXT("Number of bytes:\t%x\n"), dwNumberOfBytesTransfered);
   g_BytesTransferred = dwNumberOfBytesTransfered;
}

HANDLE hFile;
DWORD  dwBytesRead = 0;
char   ReadBuffer[BUFFERSIZE] = { 0 };
OVERLAPPED ol = { 0 };
hFile = CreateFile(fullFilePath.c_str(),               // 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 | FILE_FLAG_OVERLAPPED, // normal file
    NULL);                 // no attr. template

ReadFileEx(hFile, ReadBuffer, BUFFERSIZE - 1, &ol, FileIOCompletionRoutine);

When I print ReadBuffer It's just MZ(exe file).

But Using:

std::ifstream file(argv[1], std::ios::in | std::ios::binary);

It's work perfectly. How Can I Read Binary files With ReadFile?

Upvotes: 2

Views: 3036

Answers (2)

Daniel Sęk
Daniel Sęk

Reputation: 2769

How Can I Read Binary files With ReadFile?

ReadFile (and ReadFileEx ) works 'in binary mode'. You get exact file contents byte by byte without any translation.

You have problem with writing/printing. This mostly depends where you want to write, but for outputing (binary) data potentially containing nulls in C++ choose write method

some_output_stream.write( buffer_ptr, num_bytes_in_buffer );

some_output_stream should be set to binary mode (std::ios::binary). Without this flag all bytes with value 10 could be translated to pairs 13,10.

If C FILE functions are used

fwrite( buffer_ptr, 1, num_bytes_in_buffer, some_output_file );

Again some_output_file has to be in binary mode.

In some scenarios WriteFile can be used complementary to your usage of ReadFile.

Upvotes: 0

user3458
user3458

Reputation:

The problem is not with reading, the problem is with printing.

You're not showing your code, but you're likely trying to print with printf or something similar. IOW, you're printing it as C string.

Well, binary data includes 0s, and in this case the first 3 bytes are 'M', 'Z', '\0' - and that prints as a null-terminated string "MZ".

You'd have to write a converter to per-byte hex numbers if you want to see meaningful printing of binary data: 4D 5A 00 and so on

Upvotes: 2

Related Questions