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?
std::cout << buffer
expectsbuffer
to be null-terminated, but it is not. You need to allocate space for the terminator, eg:Alternatively, you can use
cout.write()
instead, then you don't need a terminator, eg: