[comp.lang.pascal] How to determine if I/O redirection is used

phys169@csc.canterbury.ac.nz (05/21/91)

In article <14165@ur-cc.UUCP>, elmo@troi.cc.rochester.edu (Eric Cabot) writes:
> 
>   I want to be able to detect if the user is redirecting standard
> input and/or standard output  on the command line. 

Look at Dos function $44 (subcall 0), which returns the device characteristics
for a given handle (handle 0 is stdin, 1 is std out, 2 is stderr, etc). If the
input is redirected to a disk file you will get something like $0043 instead of
$80D3 (or $80C0 for a COM line or printer). It is possible to determine if the
input (or output) is redirected to a file but not a device (useful when using
the CTTY COM1 command). Remember that some device characteristic bits will vary
according to version of operating system, etc (e.g. you might get $0040 when
redirecting input to a diskette file, and goodness-knows-what with networks).
What you can be sure of is: $0080 will be set if it is a device, and the two
bottom bits will be off if that device isn't the console.

I check for $8083 being set (otherwise it is a disk file or another device).
(simple demo included below)

Hope this helps,
Mark Aitchison, Physics, University of Canterbury, New Zealand.

--snip here--
program Redirection;

const StdIn = 0;
      StdOut= 1;
      StdErr= 2;

function DeviceCharacteristics(handle : word) : word;  {returns $FFFF if error}
inline($5B/$B8/$4400/$Cd/$21/$8B/$D0/$73/$03/$B8/$FFFF);
{pop BX; mov ax,$4400; int $21; mov AX,BX; jnc exit; mov AX,-1}

function IsRedirected(handle : word) : boolean; {true if redirected or error}
begin
IsRedirected:=(DeviceCharacteristics(handle) and $9083)<>$8083;
end;

begin
if IsRedirected(StdIn) then writeln('Input is redirected');
end.