How to read from the keyboard when stdin is set to a file in C

I think this is simple, but not for me, obviously!

I have a console application. I need to read keyboard input, but stdin redirected to a file. So, how do I create a FILE-Handle that points to a keyboard stream that I can use with fgets , etc.?

I found out that ttyname(0) similar to what I am looking for in a POSIX environment that I do not have. I am on a Windows system with a standard Visual Studio compiler.

Any ideas? Thank you in advance.

+4
source share
2 answers

There is no easy / portable way to find out if a keyboard exists (your application can be launched from a terminal emulator from a serial port, telnet session, or anything else). If the keyboard actually exists (including the image of the keyboard on the touch screen), then you cannot really tell how many layers of software must pass the keystrokes before they get into your application (for example, keystrokes can go from the keyboard driver to to the editor of the input method for the GUI for the shell in your application). This means that trying to get keystrokes directly from the keyboard driver or something bad that will fail in almost all cases.

The best way to solve your problem is to find out which series of design failures led to STDIN redirection in the first place.

For instance; perhaps the application should have a command line parameter to read some data from the file; so that the application can get some data from the file, and some from STDIN (and get all the data from STDIN if the command line option is missing).

+1
source

Extraction from the dark days of DOS programming here: try opening "CON:" (Console), a reserved word. Hope it opens in the same way on Windows. A colon may or may not be required. Both "dir> con:" and "dir> con" still work on the command line.

Also, do not forget to use something from the setbuf () family in the output descriptor to avoid buffering ... it should not buffer the I / O terminal, but it never hurts to be sure.

Again, I’m not sure, but I suspect opening a separate FILE *conin, *conout for output, and one for input may help if you have problems with a single descriptor that performs both input and output.

+1
source

Source: https://habr.com/ru/post/1437966/


All Articles