Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

stdin - 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<<

I know that isatty should be used to detect if stdin is a tty or not. If it’s not a tty, I want to read out the piped contents — in the above example, that’s the string hello world.

What’s the recommended way of doing this in C?

Here’s what I got so far:

#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<<
", pipe);
  }

}

I compiled this using:

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

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
?<<

Disclaimer: I have no experience with C whatsoever. Please go easy on me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The replacement symbol shows up because you forgot to NUL-terminate the string.

The newline is there because by default, echo inserts ' ' at the end of its output.

If you want to not insert ' ' use this:

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

And to remove the wrong character insert

pipe[i-1] = '';

before printing the text.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...