Jun 12 2009

Reading outputs of an external program in C++

Published by Lord TCT at 4:34 pm under Linux, Programming Tips

Linux

Ever wanted to grab the output of a command via C++?

In PHP, we are all very familiar with @exec and popen, but what about C++?

Try this:

string cmd = “/usr/bin/netstat -na”;
string OutString;
FILE *FileStream;
char stdbuffer[1024];
FileStream = popen(cmd.c_str(), “r”);
while (fgets(stdbuffer, 1024, FileStream) != NULL)
OutString.append(stdbuffer);
pclose(FileStream);

  • The first 3 lines are variable declarations.
  • This is followed by popen command which opens a pipe to the external program. r here means to read from the program output.
  • We will now use a 1024 character buffer to read the pipe until a null terminator is encountered.
  • Remember to close the process pipe once you’re done!

You ask: “What if I want to have the stderr captured as well?”. No problem! Just add:

2>&1

to the back of your command, just like how you would do it in BASH.

No responses yet

Comments RSS

Leave a Reply

Anti-spam challenge:
Sorry but you forced me to do this!