Capturing stdout from a system() command optimally [duplicate]
I'm trying to start an external application through system()
- for example, system("ls")
. I would like to capture its output as it happens so I can send it to another function for further processing. What's the best way to do that in C/C++?
Solution 1:
From the popen manual:
#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
Solution 2:
Try the popen() function. It executes a command, like system(), but directs the output into a new file. A pointer to the stream is returned.
FILE *lsofFile_p = popen("lsof", "r");
if (!lsofFile_p)
{
return -1;
}
char buffer[1024];
char *line_p = fgets(buffer, sizeof(buffer), lsofFile_p);
pclose(lsofFile_p);