0

我知道如何(或多或少)在 C 中做到这一点:

#include <stdio.h>
#include <string.h>

int
main(int argc, char** argv)
{
  char buf[BUFSIZ];
  fgets(buf, sizeof buf, stdin); // reads STDIN into buffer `buf` line by line
  if (buf[strlen(buf) - 1] == '\n')
  {
    printf("%s", buf);
  }
  return 0;
}

期望的最终结果是从管道中读取 STDIN(如果存在)。(我知道上面的代码没有这样做,但我无法弄清楚从管道/heredoc 读取时如何只执行上述操作)。

我将如何在鸡肉计划中做类似的事情?

就像我之前说的,最终目标是能够做到这一点:

echo 'a' | ./read-stdin
# a

./read-stdin << EOF
a
EOF
# a

./read-stdin <<< "a"
 # a

./read-stdin <(echo "a")
 # a

./read-stdin < <(echo "a")
 # a
4

1 回答 1

0

弄清楚了。

;; read-stdin.scm

(use posix)
;; let me know if STDIN is coming from a terminal or a pipe/file
(if (terminal-port? (current-input-port))
   (fprintf (current-error-port) "~A~%" "stdin is a terminal") ;; prints to stderr
   (fprintf (current-error-port) "~A~%" "stdin is a pipe or file"))
;; read from STDIN
(do ((c (read-char) (read-char)))
   ((eof-object? c))
   (printf "~C" c))
(newline)

根据Chicken wikiterminal-port?Chicken 相当于C 的isatty()功能。

笔记

上面的例子在编译时效果最好。运行它csi似乎terminal-port?总是返回 true,但也许在文件的末尾添加一个显式调用(exit)会导致 Chicken Scheme 解释器退出,从而允许STDIN成为终端以外的东西?

于 2014-03-23T03:49:11.413 回答