C redirect stdin to keyboard -


i have written smallish c program on mac osx following steps:

  1. reads input stdin , stores input memory.
  2. runs computations , prints output stdio

in between steps 1 , 2, want prompt user , wait kind of keyboard input signal "keep proceeding step 2". problem stdin has been redirected when program called using command:

$ ./simple < input.in 

i redirect stdin keyboard after reading file , not sure how this. have tried using

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

but stdin fails read keyboard thereafter. suggestions on how appreciated.

some further points:

  • the real program more involved simple still illustrates question.
  • the reason i'd pause program during execution have enough time load "simple" process osx app called instruments performance analysis.
  • if helps, more example code provided below.

int main(void) {      // step 1     int array[arrlen];     readinput(array, arrlen);       // wait keyboard input procede     // redefine stdin keyboard     fclose(stdin);     freopen("newin", "r", stdin);     char c[5];      char cmp[5] = ".";     puts ("enter text. include dot ('.') in sentence exit:");      while (1) {         fgets(c, sizeof(c), stdin);         printf("c = %s\n", c);         // if (strcmp(c, cmp))         //     break;         sleep(1);     }      // step 2     // here     return 0; } 

unless have file named newin want use, freopen invocation fail. (besides, must not close stream before calling freopen, since freopen expects valid stream, closes side effect.) reopen standard input read terminal, need specify /dev/tty file name:

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

if program under control, there no reason reopen stdin begin - open /dev/tty separate file pointer, , use obtain interactive input:

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

in either case, not possible automate interactive responses using shell pipes, appears want. reading /dev/tty standard practice in command-line programs support both input redirection , interactive work, such unix editors.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -