简体   繁体   中英

How to read from 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 input from the keyboard, but stdin has been redirected to a file. So how do I create a FILE-Handle that points at the keyboard-stream which i can use with fgets etc.?

I found out that ttyname(0) seems to be what i look for in a POSIX-environment, which I don't have here. I'm in a Windows-system with standard Visual Studio compiler.

Any ideas? Thank you in advance.

Pulling from the dim dark days of DOS programming here: try opening "CON:" (Console), a reserved word. Hopefully it will open the same way in Windows. The colon may or may not be required. Both "dir >con:" and "dir >con" still work in command prompt.

Also, be sure to use something from the setbuf() family on the output handle to avoid buffering... it's not supposed to buffer terminal I/O, but it never hurts to be sure.

Again, not sure, but I suspect opening separate FILE *conin, *conout for output and one for input may help if you seem to have troubles with one handle doing both input and output.

There's no easy/portable way to tell if a keyboard exists (your application may be being run from a terminal emulator from a serial port, a telnet session or anything else). If a keyboard actually does exist (including a picture of a keyboard on a touch screen), then you can't really tell how many layers of software the keystrokes need to pass through before they get to your application (eg keystrokes might go from a keyboard driver to an input method editor to a GUI to a shell to your application). This means that attempting to get keystrokes directly from a keyboard driver or something is a bad idea 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 being redirected in the first place.

For example; maybe the application should've had a command line option to read some data from a file; so that the application can get some data from the file and some from STDIN (and get all data from STDIN if the command line option isn't present).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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