0

I have a program that I start from a command line with a file pushed to 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.

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.

The program runs as C++17 but uses a lot of C style code. If you know a way how to do this with C++ streams feel free to post that as well. I use Windows 10 but I would also like to see some portable code.

10
  • 2
    Sounds to me like you're trying to hammer a square peg into a round hole. Why not just provide the input filename as a command line argument (main.exe file.bin) and keep stdin free for user input when you need it? Commented Jun 18, 2020 at 14:13
  • Open the file with fopen("File.bin", "rb") Also the code will ignore the early part if it has more than 16000 elements. Better to capture the return value from fread. Commented Jun 18, 2020 at 14:13
  • If it's running as C++17, <filesystem> is worth learning. Commented Jun 18, 2020 at 14:14
  • I know that would work, but in my environment it's currently not possible. I can only do < operation. Commented Jun 18, 2020 at 14:14
  • @sanitizedUser what makes impossible to use fopen or <filesystem> in your environment ? Commented Jun 18, 2020 at 14:18

1 Answer 1

1

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. Maybe you could try it with WinAPI https://learn.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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.