c - 标准输入上的 ReadFile 在 Windows 7 上崩溃

标签 c windows winapi

尝试使用 ReadFile 读取标准输入可以在 Windows 8+ 上运行,但在 Windows 7 上会崩溃。

#include <windows.h>

int main() {
    char c[1];
    HANDLE in = GetStdHandle(STD_INPUT_HANDLE);
    ReadFile(in, c, 1, NULL, NULL);
    return 0;
}

产生

Program received signal SIGSEGV, Segmentation fault.
0x00000000770f5803 in VerifyConsoleIoHandle () from C:\Windows\system32\kernel32.dll

在 Windows 7 上

最佳答案

the lpNumberOfBytesRead argument is required, unless the ReadFile will complete asynchronously (the file/device was opened with the correct flags and lpOverlapped is provided)

在 Windows 8 及更高版本上,在写入之前会检查此参数是否为 NULL(实际上使其成为可选),但这在任何地方都没有记录。

读取标准输入而不检查读取的字节数无论如何都是一个坏主意,因为如果输入重定向到管道,则读取的字节数可能小于请求的字节数(甚至为 0)。

关于c - 标准输入上的 ReadFile 在 Windows 7 上崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43160968/

相关文章:

c - 如何在sublime text 3中编译运行C?

c - 我没有得到想要的 o/p

c++ - 任务栏扩展(如联系人)

c - 如何在 Linux 中创建具有特定安全权限的文件? (即相当于 Win32 CreateFile+SECURITY_ATTRIBUTES)

c - 是否有一个用于 3d 旋转且舍入误差最小的简单 C 库?

c - 如何从 char 值 c 中删除子域

python - 如何从 Windows 上的 Gstreamer 子进程读取二进制数据?

linux - MenuItem 位图引发断言失败……

c++ - 函数调用以返回ListView_SetItemText宏内的字符串

c++ - 按名称链接导入 (C++/Visual Studio)