如何阅读C中的管道内容?

时间:2013-04-30 17:48:47

标签: c stdin pipe

我希望能够做到这一点:

$ echo "hello world" | ./my-c-program
piped input: >>hello world<<

我知道isatty should be used来检测stdin是否是tty。如果它不是tty,我想读出管道内容 - 在上面的例子中,那是字符串hello world

在C中推荐的方法是什么?

这是我到目前为止所得到的:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char* argv[]) {

  if (!isatty(fileno(stdin))) {
    int i = 0;
    char pipe[65536];
    while(-1 != (pipe[i++] = getchar()));
    fprintf(stdout, "piped content: >>%s<<\n", pipe);
  }

}

我用以下方法编译了这个:

gcc -o my-c-program my-c-program.c

几乎有效,除了它似乎总是在管道内容字符串的末尾添加一个U + FFFD REPLACEMENT CHARACTER和一个换行符(我确实理解换行符)。为什么会发生这种情况,以及如何避免这个问题呢?

echo "hello world" | ./my-c-program
piped content: >>hello world
�<<

免责声明:我对C没有任何经验。请放轻松我。

1 个答案:

答案 0 :(得分:7)

替换符号显示,因为您忘记了NUL终止字符串。

新行存在,因为默认情况下,echo会在其输出的末尾插入'\n'

如果您不想插入'\n',请使用:

echo -n "test" | ./my-c-program

并删除错误的字符插入

pipe[i-1] = '\0';

在打印文本之前。

请注意,您需要使用i-1作为空字符,因为您实现循环测试的方式。在你的代码中,i在最后一个字符之后再次递增。

相关问题