简体   繁体   English

ReadFile 缓冲区 output 很奇怪(打印内容 + 一些)

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

I am trying to open a file and read its content using the Win32 API:我正在尝试使用 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).我想要获取的是文件内容(在本例中为 .txt)。 What I get is the content of a.txt file + some more random chars (its different for each run).我得到的是 a.txt 文件的内容 + 一些随机字符(每次运行都不同)。

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 expects buffer to be null-terminated, but it is not. std::cout << buffer期望buffer以 null 终止,但事实并非如此。 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:或者,您可以改用cout.write() ,这样就不需要终止符,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM