Check output device is a terminal: Difference between revisions

From Rosetta Code
Content added Content deleted
(added ocaml)
m (→‎{{header|OCaml}}: lighter syntax)
Line 33: Line 33:


<lang ocaml>let () =
<lang ocaml>let () =
print_endline begin
print_endline (
if Unix.isatty Unix.stdout
if Unix.isatty Unix.stdout
then "Output goes to tty."
then "Output goes to tty."
else "Output doesn't go to tty."
else "Output doesn't go to tty."
end</lang>
)</lang>


Testing in interpreted mode:
Testing in interpreted mode:

Revision as of 07:56, 28 March 2013

In this task, the job is to check whatever output filehandle exits to the terminal and mention whatever output goes to 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() {

   puts(isatty(fileno(stdout))
         ? "stdout is tty"
         : "stdout is not tty");
   return 0;

}</lang>

Output:
$ ./a.out
stdout is tty

$ ./a.out > tmp
$ cat tmp
stdout is not tty

$ ./a.out | cat
stdout is not tty

OCaml

<lang ocaml>let () =

 print_endline (
   if Unix.isatty Unix.stdout
   then "Output goes to tty."
   else "Output doesn't go to tty."
 )</lang>

Testing in interpreted mode:

$ ocaml unix.cma istty.ml
Output goes to tty.

$ ocaml unix.cma istty.ml > tmp
$ cat tmp
Output doesn't go to tty.

$ ocaml unix.cma istty.ml | cat
Output doesn't go to tty.