我希望能够做到这一点:
$ echo "hello world" | ./my-c-program
piped input: >>hello world<<
我知道应该使用
isatty
函数来检测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替换字符和一个换行符(我理解换行符)。为什么会出现这种情况,如何避免这个问题?
echo "hello world" | ./my-c-program
piped content: >>hello world
�<<
免责声明:我对 C 语言毫无经验。请对我宽容一些。