Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I read the results of a system() call in C++?
    text
    copied!<p>I'm using the following code to try to read the results of a <code>df</code> command in Linux using <code>popen</code>.</p> <pre><code>#include &lt;iostream&gt; // file and std I/O functions int main(int argc, char** argv) { FILE* fp; char * buffer; long bufSize; size_t ret_code; fp = popen("df", "r"); if(fp == NULL) { // head off errors reading the results std::cerr &lt;&lt; "Could not execute command: df" &lt;&lt; std::endl; exit(1); } // get the size of the results fseek(fp, 0, SEEK_END); bufSize = ftell(fp); rewind(fp); // allocate the memory to contain the results buffer = (char*)malloc( sizeof(char) * bufSize ); if(buffer == NULL) { std::cerr &lt;&lt; "Memory error." &lt;&lt; std::endl; exit(2); } // read the results into the buffer ret_code = fread(buffer, 1, sizeof(buffer), fp); if(ret_code != bufSize) { std::cerr &lt;&lt; "Error reading output." &lt;&lt; std::endl; exit(3); } // print the results std::cout &lt;&lt; buffer &lt;&lt; std::endl; // clean up pclose(fp); free(buffer); return (EXIT_SUCCESS); } </code></pre> <p>This code is giving me a "Memory error" with an exit status of '2', so I can see <em>where</em> it's failing, I just don't understand <em>why</em>.</p> <p>I put this together from example code that I found on <a href="http://ubuntuforums.org/showthread.php?t=285287" rel="nofollow noreferrer">Ubuntu Forums</a> and <a href="http://en.cppreference.com/w/cpp/io/c/fread" rel="nofollow noreferrer">C++ Reference</a>, so I'm not married to it. If anyone can suggest a better way to read the results of a system() call, I'm open to new ideas.</p> <p><strong>EDIT to the original:</strong> Okay, <code>bufSize</code> is coming up negative, and now I understand why. You can't randomly access a pipe, as I naively tried to do.</p> <p>I can't be the first person to try to do this. Can someone give (or point me to) an example of how to read the results of a system() call into a variable in C++?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload