stdin and UNIX pipes

Roy Johnson rjohnson at shell.com
Wed Feb 20 10:12:51 AEST 1991


In article <92993 at unix.cis.pitt.edu> nr3m at unix.cis.pitt.edu (Matthew A Henry) writes:
>I am writing a C program in a UNIX environment that will receive input
>from other programs through a pipe, causing the shell to change the
>default assignment of stdin.  At some point in the program I would like
>to request input from the original stdin (keyboard).  Any thoughts on
>how I could do this, e-mailed or posted, would be greatly appreciated.

The file "/dev/tty" should be your keyboard for input (it is on my Sun).
I think you want something like this:

#include <stdio.h>

main()
{
  int i;

  if (freopen("newfile", "r", stdin) != stdin) {
    perror("freopen");
    exit(1);
  }
  /* Get 50 chars from "newfile" */
  for(i=0; i<50; ++i)
    putchar(getchar());

/* Change back to stdin */
  if (freopen("/dev/tty", "r", stdin) != stdin) {
    perror("freopen");
    exit(1);
  }
  /* Get 50 chars from keyboard */
  for(i=0; i<50; ++i)
    putchar(getchar());
}
--
======= !{sun,psuvax1,bcm,rice,decwrl,cs.utexas.edu}!shell!rjohnson =======
Feel free to correct me, but don't preface your correction with "BZZT!"
Roy Johnson, Shell Development Company



More information about the Comp.lang.c mailing list