我知道如何(或多或少)在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。(我知道上面的代码不会这样做,但我不知道如何只在从管道/本地文档读取时才这样做)。
在鸡肉计划中,我怎样做类似的事情呢?
就像我之前说过的,最终目标是能够做到这一点:
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发布于 2014-03-23 03:49:11
弄明白了。
;; 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)根据鸡的维基,terminal-port?是鸡的isatty()函数。
注意事项
上面的例子在编译时效果最好。使用csi运行它似乎使terminal-port?总是返回true,但也许向(exit)和文件的第四端添加一个显式调用会导致file解释器退出,从而允许STDIN不是终端?
https://stackoverflow.com/questions/22523226
复制相似问题