简体   繁体   English

从标准输入读取文件后读取用户输入

[英]Reading user input after reading a file from stdin

I have a program that I start from a command line with a file pushed to stdin :我有一个程序,我从命令行开始,将文件推送到stdin

main.exe < file.bin

I read all the contents from the file like so:我从文件中读取了所有内容,如下所示:

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

After all numbers are read, I would like the user to confirm continuation in the program by pressing any key but at that point stdin probably contains EOF and the program skips the confirmation from the user.读取所有数字后,我希望用户通过按任意键确认程序继续,但此时stdin可能包含EOF并且程序会跳过用户的确认。

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

Here's the whole program if you want to reproduce it.如果您想重现它,这是整个程序。 But to reproduce you have to push a file to stdin before execution.但是要重现,您必须在执行之前将文件推送到标准输入。

#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;
}

The question is how to make the getchar() call take an character from the user's keyboard and not the file that was already read.问题是如何使getchar()调用从用户的键盘中获取一个字符,而不是从已经读取的文件中获取。

The program runs as C++17 but uses a lot of C style code.该程序以 C++17 运行,但使用了大量 C 样式代码。 If you know a way how to do this with C++ streams feel free to post that as well.如果您知道如何使用 C++ 流来做到这一点,请随时发布。 I use Windows 10 but I would also like to see some portable code.我使用 Windows 10 但我也想看看一些可移植的代码。

If you use a file file.bin as a stdin via main.exe < file.bin , you cannot simultaneously use console as a stdin using standard C or C++ libraries.如果通过main.exe < file.bin将文件file.bin用作标准输入,则不能同时使用标准 C 或 C++ 库将控制台用作标准输入。 Maybe you could try it with WinAPI https://docs.microsoft.com/en-us/windows/console/readconsoleinput And using std::cin to read binary data is unfortulately not possible: Read binary data from std::cin也许您可以尝试使用 WinAPI https: //docs.microsoft.com/en-us/windows/console/readconsoleinput 不幸的是,使用 std::cin 读取二进制数据是不可能的: 从 std::cin 读取二进制数据

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

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