title: Reading popen results in C++
body: <p>I am writing a C++ application and I need to read the result of a system command.</p>
  
  <p>I am using <code>popen()</code> more or less as shown here:</p>
  
  <pre><code>    const int MAX_BUFFER = 2048;
      string cmd="ls -l";
      char buffer[MAX_BUFFER];
      FILE *stream = popen(cmd.c_str(), "r");
      if (stream){
         while (!feof(stream))
         {
              if (fgets(buffer, MAX_BUFFER, stream) != NULL)
              {
                 //here is all my code
              }
         }
         pclose(stream);
      }
  </code></pre>
  
  <p>I've been trying to re-write this in a different way. I saw some non-standard solutions like:</p>
  
  <pre><code>FILE *myfile;
  std::fstream fileStream(myfile);
  std::string mystring;
  while(std::getline(myfile,mystring))
  {
      // .... Here I do what I need
  }
  </code></pre>
  
  <p>My compiler does not accept this though.</p>
  
  <p>How can I read from <code>popen</code> in C++?</p>