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.

The ttyname function wouldn't have helped in a POSIX environment, as it would return NULL when input is coming from a pipe or a redirected file.
–
Joachim PileborgOct 5 '12 at 9:45

stdin has been redirected to a file. - why dont you fclose that file pointer and freopen stdin to a new file. Once you are done then again redirected stdin to the old file.
–
nav_janOct 5 '12 at 9:57

In a way, that is what I want to do nav_jan, but if I don't know the path to the console, I can't open it using fopen or freopen. If i have that path, I wouldnt need to redirect stdin. I could just create another handle for keyboard input, and use both file- and keyboardinput independently. But thanks for the thought.
–
Sascha LeyerOct 5 '12 at 10:30

2 Answers
2

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 (e.g. 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).

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.