Getting stdin after using the redirection operator <

To assign programming, we fulfill the following requirements:

  • It must be a command line program written in C.
  • He should read the text from a text document. However, we must do this using the Unix redirection operator <when ​​starting the program, and not when loading the program with the file itself. (Thus, the program reads the text, pretending to read from stdin.)
  • After reading the data from the file, the program should interview the user for more information before doing their job.

After much research, I cannot find a way to get the "old" stdin to complete part (3). Does anyone know how this is possible?

Technically, part (3) is part of the bonus section, which the teacher probably did not realize himself (very long), so it is possible that this is impossible, and this is supervision on his part. However, of course, I do not want to do this.

+2
source share
3 answers

In linux, I would open the control terminal / dev / tty.

+5
source

Which OS? On Linux, the usual trick for doing this is to verify that stderr is still connected to tty:

 if (isatty(2)) 

and if so, open a new read file descriptor for this terminal:

 new_stdin = open("/proc/self/fd/2", O_RDONLY); 

then duplicate the new file descriptor on stdin (which closes the old stdin):

 dup2(new_stdin, 0); 

(If stderr is also redirected, then isatty(2) will return false, and you will have to refuse.)

+3
source

If you run the program as follows:

 myprog 3<&0 < filename 

then you will get file descriptor 3 created for you as a duplicate of stdin . I do not know if this meets the requirements of your assignment, but it may be worth the experiment.

+1
source

All Articles