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

我希望能够做到这一点:

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

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

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

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

 #include  #include  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没有任何经验。 请放轻松我。

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

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

如果你不想插入'\n'使用:

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

并删除错误的字符插入

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

在打印文本之前。

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