How to determine file being redirected to in C
Michael Davidson
md at sco.COM
Wed Mar 1 08:34:53 AEST 1989
In article <10 at sherpa.UUCP> rac at sherpa.UUCP (Roger A. Cornelius) writes:
>Anyway, can someone tell me how to determine (in C)
>if output is being redirected, or more precisely, how to determine the
>file output is being redirected to.
You can determine the type of file associated with your
standard output (or any other file descriptor) by using
fstat(). This will tell you the type of file (regular,
block special, character special, fifo) and the device
and inode #.
There is no easy way of going from a device and inode #
to a pathname, short of searching through the entire
directory hierarchy on the appropriate filesystem (or
invoking ncheck to do it for you) - remember also that
the file may have many links to it or, by the time you
go looking for the path name, it may have none....
cat simply checks whether it's output has been redirected
to a regular file and, if it has, does a stat() of each of
it's input files, comparing device and inode # with that
of the output file - if it finds a match it reports the
error "cat: input foo is output".
More information about the Comp.unix.questions
mailing list