如何读取C管道的内容? [英] How to read piped content in C?
问题描述
我希望能够做到这一点:
I want to be able to do this:
$ echo "hello world" | ./my-c-program
piped input: >>hello world<<
我知道, isatty
应使用以检测是否标准输入是一个tty与否。如果它不是一个TTY,我想读出管道的内容 - 在上面的例子,这是字符串的Hello World
什么是用C这样做的推荐的方法?
What’s the recommended way of doing this in 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替换字符,并在管道内容字符串的结尾换行符(我虽然明白换行)。为什么会发生这种情况,以及如何避免这个问题?
It almost works, except it always seems to add a U+FFFD REPLACEMENT CHARACTER and a newline (I do understand the newline though) at the end of the piped content string. Why does this happen, and how can this issue be avoided?
echo "hello world" | ./my-c-program
piped content: >>hello world
�<<
声明:我用C没有任何经验。请宽容我。
Disclaimer: I have no experience with C whatsoever. Please go easy on me.
推荐答案
替代符号显示出来,因为你忘了NUL,终止字符串。
The replacement symbol shows up because you forgot to NUL-terminate the string.
换行符是存在的,因为在默认情况下,回声
插入的'\\ n'
在其输出的结尾。
The newline is there because by default, echo
inserts '\n'
at the end of its output.
如果你想不插入的'\\ n'
使用:
echo -n "test" | ./my-c-program
和删除错误的字符插入
pipe[i-1] = '\0';
在打印文本。
请注意,你需要,因为你的方式来实现你的循环测试中使用 I-1
作为空字符。在您code I
递增的最后一个字符后的一次。
Note that you need to use i-1
as the null character because the way you implemented your loop test. In you code i
is incremented once more after the last char.
这篇关于如何读取C管道的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!