ReadFile() 缓冲区使用 printf() 打印垃圾?

问题描述 投票:0回答:1

尝试从现有文件 (test.txt) 创建句柄,读取数据以缓冲并使用 printf 打印缓冲区。

显然一切正常——没有错误,ReadFile 读取的字节数是正确的。但是当我用 printf 打印缓冲区时,从 txt 文件到屏幕的数据后打印了一些垃圾:

enter image description here

代码是:

#include <windows.h>
#include <stdio.h>

WCHAR input_file[9] = L"test.txt";
LPCWSTR p_input_file = input_file;

#define BUFFER_SIZE 24

int main()
{
    HANDLE hFile = NULL;
    CHAR inBuffer[BUFFER_SIZE];
    LPVOID pbuffer = inBuffer;
    DWORD nNumberOfBytesToRead = BUFFER_SIZE;
    DWORD nNumberOfBytesRead;

    hFile = CreateFile(input_file,               
        GENERIC_READ,          
        FILE_SHARE_READ,       
        NULL,                  
        OPEN_EXISTING,         
        FILE_ATTRIBUTE_NORMAL, 
        NULL);                 

    BOOL reading_result = ReadFile(hFile,
        pbuffer,
        nNumberOfBytesToRead,
        &nNumberOfBytesRead,
        NULL);

    int error_code_value = GetLastError();

    if (error_code_value == 0)
    {
        printf("Work properly. The text is: %s \n", inBuffer);
    }
    else if (error_code_value == ERROR_INVALID_HANDLE)
    {
        printf("Handle is loaded in invalid way.\n");
    }
    else
    {
        printf("Worked wrong. error code: %d. \n", GetLastError());
    }


    CloseHandle(hFile);
}
c++ winapi
1个回答
0
投票

尝试使用 null 初始化 inBuffer:

#include <windows.h>
#include <stdio.h>

WCHAR input_file[9] = L"test.txt";
LPCWSTR p_input_file = input_file;

#define BUFFER_SIZE 24

int main()
{
    HANDLE hFile = NULL;
    CHAR inBuffer[BUFFER_SIZE];
    LPVOID pbuffer = inBuffer;
    DWORD nNumberOfBytesToRead = BUFFER_SIZE;
    DWORD nNumberOfBytesRead;
    memset(inBuffer, 0, sizeof(inBuffer)); // Initialize with null / 0

    hFile = CreateFile(input_file,
        GENERIC_READ,
        FILE_SHARE_READ,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    BOOL reading_result = ReadFile(hFile,
        pbuffer,
        nNumberOfBytesToRead,
        &nNumberOfBytesRead,
        NULL);

    int error_code_value = GetLastError();

    if (error_code_value == 0) {
        printf("Work properly. The text is: %s \n", inBuffer);
    } else if (error_code_value == ERROR_INVALID_HANDLE) {
        printf("Handle is loaded in invalid way.\n");
    } else {
        printf("Worked wrong. error code: %d. \n", GetLastError());
    }


    CloseHandle(hFile);
    return 0;
}

[Output_Screenshot][1]
[1]: https://i.stack.imgur.com/ggchZ.png
© www.soinside.com 2019 - 2024. All rights reserved.