How to determine file being redirected to in C

Frank Bicknell frankb at usource.UUCP
Wed Mar 1 00:59:38 AEST 1989


In article <10 at sherpa.UUCP>, rac at sherpa.UUCP (Roger A. Cornelius) writes:
> ... 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. ...  

I presume you know how to determine whether the std* is directed
to a terminal with isatty().

Your request seemed to hint at being able to determine whether
the stdout and a file given in *argv[] were the same file.
One way which comes to mind (this might be the hard way) is
to use stat() on the file and fstat() on stdout.  Then you
compare st_ino and st_dev in both returned structures.  If both
sets match (ie r.st_ino == f.st_ino && r.st_dev == f.st_dev)
then they must be the same file.  (Network fans: is this true
for remotely-mounted filesystems?)

As for the general case of finding out the name of the file to
which output (input) has been redirected to (from), that's more
difficult, I think.  The only way which comes to mind is to take
that inode number and device id from fstat() and run system
("ncheck -i inode filesystem") on them.  This takes a while, but
beats rewriting the code to search through the directory
structure (and your code would take as long as theirs, I would
assume).
-- 
Frank Bicknell; 1405 Main St, Ste 709; Sarasota, FL 34236-5701
killer!usource!frankb



More information about the Comp.unix.questions mailing list