hack のためのネタ帳, etc,,,

標準入出力(stdio) が TeleTYpe かどうか調べる関数

マニュアル

参考になるページ等

サンプル

isatty.c

#include <stdio.h>
#include <stdlib.h>

#ifdef _WIN32
#include <io.h>
#define TTY "CON:"
#else
#include <unistd.h>
#define TTY "/dev/tty"
#endif

int main()
{
  FILE *ttyin;
  FILE *ttyout;
  int x = -1;
  int y = -1;
  
  ttyin = fopen(TTY, "r");
  if (ttyin == NULL) {
    fprintf(stderr, "Error: can not read open file: %s\n", TTY);
    return EXIT_FAILURE;
  }
  ttyout = fopen(TTY, "w");
  if (ttyout == NULL) {
    fprintf(stderr, "Error: can not write open file: %s\n", TTY);
    return EXIT_FAILURE;
  }
  fscanf(stdin, "%d", &x);
  fscanf(ttyin, "%d", &y);
  fprintf(stdout, "stdout: %d %d %d %d %d\n", isatty(fileno(stdin)), isatty(fileno(stdout)), isatty(fileno(stderr)), x, y);
  fprintf(stderr, "stderr: %d %d %d %d %d\n", isatty(fileno(stdin)), isatty(fileno(stdout)), isatty(fileno(stderr)), x, y);
  fprintf(ttyout, "ttyout: %d %d %d %d %d\n", isatty(fileno(stdin)), isatty(fileno(stdout)), isatty(fileno(stderr)), x, y);
  fclose(ttyout);
  fclose(ttyin);
  
  return EXIT_SUCCESS;
}
実行例
$ gcc isatty.c
$ echo 3 | ./a
5
stdout: 0 1 1 3 5
stderr: 0 1 1 3 5
ttyout: 0 1 1 3 5
$ ./a &>/dev/null
3
5
ttyout: 1 0 0 3 5
$ ./a >/dev/null
3
5
stderr: 1 0 1 3 5
ttyout: 1 0 1 3 5
$ ./a 2>/dev/null
3
5
stdout: 1 1 0 3 5
ttyout: 1 1 0 3 5
タグ

コメントをかく


「http://」を含む投稿は禁止されています。

利用規約をご確認のうえご記入下さい

Wiki内検索

フリーエリア

管理人/副管理人のみ編集できます