title: popen() writes output of command executed to cout
body: <p>I am writing an application that needs to open another process and get its output. Everywhere I've read online says I have to use <code>popen</code> and read from the file.</p>
  <p>But I can't read from it. The output of the command gets outputted into the console window of the calling application. Below is the code I am using. I added some prints to debug.</p>
  <pre class="lang-cpp prettyprint-override"><code>#include &lt;string&gt;
  #include &lt;iostream&gt;
  #include &lt;cstdlib&gt;
  #include &lt;cstdio&gt;
  #include &lt;array&gt;
  
  int main()
  {
      // some command that fails to execute properly.
      std::string command(&quot;ls afskfksakfafkas&quot;);
  
      std::array&lt;char, 128&gt; buffer;
      std::string result;
  
      std::cout &lt;&lt; &quot;Opening reading pipe&quot; &lt;&lt; std::endl;
      FILE* pipe = popen(command.c_str(), &quot;r&quot;);
      if (!pipe)
      {
          std::cerr &lt;&lt; &quot;Couldn't start command.&quot; &lt;&lt; std::endl;
          return 0;
      }
      while (fgets(buffer.data(), 128, pipe) != NULL) {
          std::cout &lt;&lt; &quot;Reading...&quot; &lt;&lt; std::endl;
          result += buffer.data();
      }
      auto returnCode = pclose(pipe);
  
      std::cout &lt;&lt; result &lt;&lt; std::endl;
      std::cout &lt;&lt; returnCode &lt;&lt; std::endl;
  
      return 0;
  }
  </code></pre>
  <p>Reading is never actually printed to my <code>cout</code> and result is an empty string. I clearly see the output of the command in my terminal. If the command exits gracefully the behaviour is as expected. But I only capture the output for error cases.</p>