为什么 ReadFile 函数将垃圾写入缓冲区?

Why ReadFile function writes garbage to buffer?

假设我决定使用 CreateFile 函数打开现有文件。文件内容为Hello world。还有一个缓冲区(大小为 11 且填充为零字节的字符数组)应包含文件的内容。

并且当我尝试使用 ReadFile 函数读取文件时,某些垃圾被写入缓冲区。调试器(我试过 GDB 和 LLDB)说读取后缓冲区的内容是 7?H[=15=]0e[=15=]0l[=15=]0l[=15=]0o[=15=]0[=15=]0w[=15=]0o[=15=]0r[=15=]0l[=15=]0d[=15=]0\r[=15=]0\n[=15=]0\r[=15=]0 \n, '[=15=]0',以人类可读的形式,它看起来像这样 ■ H.

我试过不用零填充缓冲区。我试着先写(用WriteFile)到一个文件,然后再读。我还尝试使用 ReadFile 更改要读取的字节数的值。但它仍然没有改变任何东西。

此外,GetLastError returns ERROR_SUCCESS

代码:

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    HANDLE file = CreateFile("./test_file.txt", GENERIC_READ, FILE_SHARE_READ, 
                             NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

    if (file == INVALID_HANDLE_VALUE) {
        puts("Failed to open");

        return EXIT_FAILURE;
    }

    size_t length = strlen("Hello world"); /* 11 */
    char buffer[12];
    DWORD count = 0; /* Is always 11 (length of "Hello world") after reading */

    memset(buffer, '[=10=]', length + 1);

    if (!ReadFile(file, buffer, (DWORD) length, &count, NULL)) {
        puts("Failed to read or EOF reached.");

        CloseHandle(file);

        return EXIT_FAILURE;
    }

    printf("buffer: '%s'\n", buffer);
    printf("count: %lu\n", count);

    CloseHandle(file);

    return EXIT_SUCCESS;
}

在控制台中,程序的输出如下所示:

buffer: ' ■ H'
count: 11

文本文件本身并没有写在文件前面的 7 位 ASCII or 8bit UTF-8 byte encoding, like you are expecting. It is actually written in a UTF-16 byte encoding, with a BOM(UTF-16LE 为字节 0xFF 0xFE)。您只是读取文件的原始字节并按原样显示它们,而不考虑它们的编码。