I'm writing a function, which, given an argument, will either redirect the stdout to a file or read the stdin from a file. To do this I close the file descriptor associated with the stdout or stdin, so that when I open the file it opens under the descriptor that I just closed. This works, but the problem is that once this is done, I need to restore the stdout and stdin to what they should really be.
What I can do for stdout is open("/dev/tty",O_WRONLY);
but I'm not sure why this works, and more importantly I don't know of an equivalent statement for stdin.
So I have, for stdout
close(1);
if (creat(filePath, O_RDWR) == -1)
{
exit(1);
}
and for stdin
close(0);
if (open(filePath, O_RDONLY) == -1)
{
exit(1);
}
O_RDWR
is foropen
flags
parameter not forcreat
mode
parameter.