C redirect stdin to keyboard

I wrote a small program on Mac OSX that performs the following steps:

  • reads some data from stdin and stores the input data in memory.
  • performs some calculations and outputs to stdio

In the intervals between steps 1 and 2, I want to invite the user and wait for any input to be entered on the keyboard so that the signal "continues to go to step 2". The problem is that stdin was redirected when the program was called using the command:

$ ./simple < input.in 

I would like to redirect stdin to the keyboard after reading the file and don't know how to do it. I tried using

 fclose(stdin); freopen("newin", "r", stdin); 

but after that stdin is not read from the keyboard. Any suggestions on how to do this would be greatly appreciated.

Some additional points:

  • The real program is much more complex than this, but the simple one still illustrates my question.
  • The reason for this is because I want to pause my program at runtime so that I have enough time to load the β€œsimple” process into an OSX application called performance analysis tools.
  • If this helps, below is an example code example.

 int main(void) { // STEP 1 int array[ARRLEN]; readinput(array, ARRLEN); // WAIT FOR KEYBOARD INPUT TO PROCEDE // redefine stdin to keyboard fclose(stdin); freopen("newin", "r", stdin); char c[5]; char cmp[5] = "."; puts ("Enter text. Include a dot ('.') in a sentence to exit:"); while (1) { fgets(c, sizeof(c), stdin); printf("c = %s\n", c); // if (strcmp(c, cmp)) // break; sleep(1); } // STEP 2 // do something here return 0; } 
+7
c stdin instruments
source share
1 answer

If you do not have a file named newin that you want to use, your freopen call will fail. (In addition, you should not close the stream before calling freopen , since freopen expects a valid stream, which it closes as a side effect.) To reopen standard input for reading from the terminal, you need to specify /dev/tty as the file name:

 if (!freopen("/dev/tty", "r", stdin)) { perror("/dev/tty"); exit(1); } 

If the program is under your control, there is no reason to reopen stdin to start - just open /dev/tty as a separate file pointer and use it to get interactive input:

 FILE *tty = fopen("/dev/tty", "r"); if (!tty) { perror("/dev/tty"); exit(1); } ... while (1) { fgets(c, sizeof(c), tty); ... } 

In any case, it is not possible to automate interactive responses using shell pipes, but it looks like what you want. Reading from /dev/tty is standard practice in command programs that support both input redirection and interactive work, for example, some Unix editors.

+3
source share

All Articles