views:

116

answers:

2

I wanna build a console app that may stop and prompt for some input, under some conditions. But I want to prompt only if input will be available.

Is there a way to know if Stdin is connected to anything?

I think powershell does this, and I'd like to do something similar. Powershell detects when it is run interactively, and prompts when that is true. I think it is also possible to force powershell into non-interactive mode. (Correct me if I am wrong)

I guess I'm thinking there are several possibilities, including but not limited to:

  • the program is running interactively in a cmd.exe prompt. In this case, prompt for input.
  • the program is running within a script, and something haas been piped to stdin. In this case, no prompt.
  • the program is running within a script, which is running in a cmd.exe prompt. In which case, prompt.
  • the program is running from within another program, and nothing has been piped to stdin. In this case, no prompt.

Is it possible for a console app to distinguish between these situations and modify behavior accordingly?

+1  A: 

I'm not certain about checking the availability of stdin, but a possible option is to accept a command line argument (like --noprompt or something) and use it when executing in a non-interactive environment.

statenjason
Good idea.I know that powershell v1.0 has such an option. I think it is (-i).
Cheeso
+3  A: 

Check out the GetStdHandle API. Calling GetStdHandle(STD_INPUT_HANDLE) will return NULL if there is no associated stdin for the application.

ScottTx