How to determine file being redirected to in C

Dave Hammond daveh at marob.MASA.COM
Wed Mar 1 22:35:40 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.  The cat command does this [...]
>
>	cat catfile > catfile
>produces the error "cat: input catfile is output".

1. Determine if your stdout has been redirected (isatty(fileno(stdout)) will
   fail if stdout is redirected).

2. Do an fstat() on fileno(stdout), and a stat() on the other file in question.

3. Compare the st_ino and st_dev members of the two stat structures.  If the
   inode (st_ino) and device-of-directory-entry (st_dev) for the two match,
   your standard output and the other file are the same.

Hope this helps.

--
Dave Hammond
daveh at marob.masa.com



More information about the Comp.unix.questions mailing list