0xPwn
0xPwn

Reputation: 385

How to read a file using readfile on Winapi

I'm learning how to use in Winapi And I'm trying to read a file from My Computer But for some reason it doesn't work ...

HANDLE hFile;
//PVOID First_Bytes[2048];
char First_Bytes[2048];
DWORD dbr = 0;
hFile = CreateFile(L"d:\\My-File",GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL , NULL);   
if (hFile == INVALID_HANDLE_VALUE) {
    printf("Error %x", GetLastError());
    return 1;
}
if (ReadFile(hFile, &First_Bytes, 512, &dbr, NULL) == 0) {
    printf("ReadFile error: %x", GetLastError());
    return 1;
}
printf("%s", First_Bytes);
CloseHandle(hFile);

The console doesn't print anything.

What am I doing wrong?

Upvotes: 0

Views: 1986

Answers (1)

David Heffernan
David Heffernan

Reputation: 612784

The logical conclusion is that the first byte in your file is a zero. You treat the buffer as a null-terminated string, and so nothing is printed.

Do note that there is no guarantee that your buffer is null terminated so you potentially have undefined behaviour.

Upvotes: 2

Related Questions