Check input device is a terminal: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|D}}: add input redirect test)
Line 36: Line 36:
}</lang>
}</lang>
{{out}}
{{out}}
<pre>test
<pre>C:\test
Input comes from tty.
Input comes from tty.
test < in.txt
C:\test < in.txt
Input doesn't come from tty.</pre>
Input doesn't come from tty.</pre>



Revision as of 23:29, 12 February 2013

Check input device is a terminal is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

In this task, the job is to check whatever input filehandle comes from terminal and mention whatever input comes from it or not.

C

Use isatty() on file descriptor to determine if it's a TTY. To get the file descriptor from a FILE* pointer, use fileno: <lang c>#include <unistd.h> //for isatty()

  1. include <stdio.h> //for fileno()

int main(void) { puts(isatty(fileno(stdin)) ? "stdin is tty" : "stdin is not tty"); return 0; }</lang>

Output:
$ ./a.out
stdin is tty
$ ./a.out < /dev/zero
stdin is not tty
$ echo "" | ./a.out
stdin is not tty

D

<lang d>import std.stdio;

extern(C) int isatty(int);

void main() {

   if (isatty(0))
       writeln("Input comes from tty.");
   else
       writeln("Input doesn't come from tty.");

}</lang>

Output:
C:\test
Input comes from tty.
C:\test < in.txt
Input doesn't come from tty.

Perl

<lang perl>use strict; use warnings; use 5.010; if (-t) {

   say "Input comes from tty.";

} else {

   say "Input doesn't come from tty.";

}</lang>

$ perl istty.pl
Input comes from tty.
$ true | perl istty.pl
Input doesn't come from tty.

Perl 6

<lang perl6>say $*IN.t ?? "Input comes from tty." !! "Input doesn't come from tty.";</lang>

$ perl6 istty.p6
Input comes from tty.
$ true | perl6 istty.p6
Input doesn't come from tty.

Python

<lang python>from sys import stdin if stdin.isatty():

   print("Input comes from tty.")

else:

   print("Input doesn't come from tty.")</lang>
$ python istty.pl
Input comes from tty.
$ true | python istty.pl
Input doesn't come from tty.

REXX

<lang rexx>/*REXX program determines if input comes from terminal or standard input*/

if queued() then say 'input comes from the terminal.'

            else say 'input comes from the (stacked) terminal queue.'
                                      /*stick a fork in it, we're done.*/

</lang>

Tcl

Tcl automatically detects whether stdin is coming from a terminal (or a socket) and sets up the channel to have the correct type. One of the configuration options of a terminal channel is -mode (used to configure baud rates on a real serial terminal) so we simply detect whether the option is present. <lang tcl>if {[catch {fconfigure stdin -mode}]} {

   puts "Input doesn't come from tty."

} else {

   puts "Input comes from tty."

}</lang> Demonstrating:

$ tclsh8.5 istty.tcl 
Input comes from tty.
$ tclsh8.5 istty.tcl </dev/null
Input doesn't come from tty.