从stdin读取文件后读取用户输入

时间:2020-06-18 14:09:01

标签: c++ c

我有一个程序是从命令行启动的,文件被推送到stdin

main.exe < file.bin

我从文件中读取所有内容,如下所示:

freopen(NULL, "rb", stdin);    // it's a binary file
long* buffer = new long[16000];
while ( fread(buffer, sizeof(long), 16000, stdin) == 16000);

在读取所有数字之后,我希望用户通过按任意键来确认程序中的继续,但是此时stdin可能包含EOF,并且程序跳过了来自用户的确认。

printf("Press any key to continue");
getchar();    // user doesn't get a chance to press anything, program flows right through 

如果您想复制它,这里是整个程序。但是要重现,必须在执行之前将文件推送到stdin。

#include <stdio.h>

int main()
{
    freopen(NULL, "rb", stdin);
    long* buffer = new long[16000];
    while ( fread(buffer, sizeof(long), 16000, stdin) == 16000);
    printf("Press any key to continue");
    getchar();
    delete[] buffer;
    return 0;
}

问题是如何使getchar()调用使用用户键盘上的字符而不是已读取的文件。

该程序作为C ++ 17运行,但是使用了大量的C风格代码。如果您知道一种使用C ++流执行此操作的方法,请随时发布。我使用Windows 10,但也希望看到一些可移植的代码。

1 个答案:

答案 0 :(得分:1)

如果通过file.bin将文件main.exe < file.bin用作标准输入,则不能使用标准C或C ++库同时将控制台用作标准输入。也许您可以使用WinAPI https://docs.microsoft.com/en-us/windows/console/readconsoleinput进行尝试 不幸的是,无法使用std :: cin读取二进制数据:Read binary data from std::cin

相关问题