Archive for the 'Programming Tips' Category

Jun 12 2009

Reading outputs of an external program in C++

Published by Lord TCT under Linux, Programming Tips

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

Mar 22 2008

VB Tips #1: Visual Basic PowerPack

Published by Lord TCT under Visual Basic

Surprisingly, one of the most useful extension to Microsoft Visual Studio goes largely unnoticed: Visual Basic PowerPack.

Think of Visual Basic PowerPack as the managed code reincarnation of a collection controls that made life easy on VB6 but were dropped since VB7:

Controls include PrintForm, LineShape, OvalShape, RectangleShape and DataRepeater. Oh those good old days are back!

No responses yet