ReadFile buffer output is weird (prints content + some more)

79 views Asked by At

I am trying to open a file and read its content using the Win32 API:

HANDLE hFileRead = CreateFileA(FilePath,
                               GENERIC_READ,
                               0,
                               NULL,
                               OPEN_EXISTING,
                               FILE_ATTRIBUTE_NORMAL,
                               NULL);

LARGE_INTEGER fileSize = { 0 };
DWORD cbFileSize = GetFileSizeEx(hFileRead, &fileSize);

PBYTE buffer = (PBYTE)HeapAlloc(GetProcessHeap(), 0, fileSize.QuadPart);
DWORD dwBytesRead = 0;

NTSTATUS s = ReadFile(hFileRead,
                      buffer,
                      fileSize.QuadPart,
                      &dwBytesRead,
                      NULL);

std::cout << buffer << "\n"; // <<< expect to print "asdasd" but prints "asdasd"+random chars (1 or more each run)

What I want to get is the file content (.txt in this case). What I get is the content of a .txt file + some more random chars (its different for each run).

I tried to write the buffer indexed, it seems that the buffer prints more than its size (?)

What am I doing wrong?

1

There are 1 answers

0
Remy Lebeau On BEST ANSWER

std::cout << buffer expects buffer to be null-terminated, but it is not. You need to allocate space for the terminator, eg:

PBYTE buffer = (PBYTE)HeapAlloc(GetProcessHeap(), 0, fileSize.QuadPart + 1);
...
buffer[dwBytesRead] = 0;

Alternatively, you can use cout.write() instead, then you don't need a terminator, eg:

std::cout.write(buffer,dwBytesRead);