Check input device is a terminal

From Rosetta Code
Revision as of 12:15, 25 September 2012 by rosettacode>Dkf (→‎Tcl: Added implementation)
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

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.

Tcl

<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.