title: How to read piped content in C?
body: <p>I want to be able to do this:</p>
  
  <pre><code>$ echo "hello world" | ./my-c-program
  piped input: &gt;&gt;hello world&lt;&lt;
  </code></pre>
  
  <p>I know that <a href="http://www.cs.rutgers.edu/~pxk/416/notes/c-tutorials/isatty.html" rel="noreferrer"><code>isatty</code> should be used</a> 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 <code>hello world</code>.</p>
  
  <p>What’s the recommended way of doing this in C?</p>
  
  <p>Here’s what I got so far:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  
  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: &gt;&gt;%s&lt;&lt;\n", pipe);
    }
  
  }
  </code></pre>
  
  <p>I compiled this using:</p>
  
  <pre><code>gcc -o my-c-program my-c-program.c
  </code></pre>
  
  <p>It <em>almost</em> 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?</p>
  
  <pre><code>echo "hello world" | ./my-c-program
  piped content: &gt;&gt;hello world
  �&lt;&lt;
  </code></pre>
  
  <p><strong>Disclaimer:</strong> I have no experience with C whatsoever. Please go easy on me.</p>