Reading the result of system()

Jul 18, 2011 at 8:25am
Hi I'm very new to this so sorry if this is extremely obvious, but I was wondering how do you read the result that is given after using the system() function from <cstdlib>?

For example if a wrote:

system("ping 11.11.11.111");

I would expect the result to be something like:

1
2
3
4
5
6
7
8
9
10
11
Pinging 11.11.11.111 with 32 bytes of data:

Reply from 11.11.11.111: bytes+32 time<1ms TTL=128
Reply from 11.11.11.111: bytes+32 time<1ms TTL=128
Reply from 11.11.11.111: bytes+32 time<1ms TTL=128
Reply from 11.11.11.111: bytes+32 time<1ms TTL=128

Ping statistics for 11.11.11.111:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms


I don't need to take in all this information, in fact I basically just need to know if I received a reply at all. But I just don't know how to read this information in. I tried using ReadConsoleOutputCharacter() from <windows.h> but I couldn't get any results that made any sense.

Does anybody know a function that will do this? Or am I just going about the whole situation the wrong way?
Jul 19, 2011 at 12:17am
I'm afraid it's more complex than a simple function call.

The most platform-independent, but least robust, way to do this is to redirect the output of ping to a file, then have your program read the file.

If that isn't sufficient, then you have to say what platform this is on. If Unix/Linux, you might try searching the UNIX/Linux Programming forum because the question of capturing output from a child process has been answered several times there.
Jul 19, 2011 at 1:59am
Hi jsmith, thanks for the reply.
It's on a windows system, sorry I should have said that.

So do you think the best way to do it is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdlib> // Declare "system()"

using namespace std;

int main()
{
	vector<string> results;
	
	system("ping 44.4.22.22 > pingresult.txt");	//if the file doesn't already exist it will create it
	system("exit");	     //this maybe doesn't have to be here

	//reads each line and stores it as a string in the array 'results'
	ifstream in("pingresult.txt");					
	string line;
	while(getline(in, line))
    results.push_back(line); // Add the line to the end
}


I would mark this as solved but it feels like there is defiantly a better way to do it, I just can't seem to find it, so if anybody has any other ideas I'd love to hear them.

Thanks.

EDIT: if you want the results to be replaced each time the code runs though keep vector<string> results;
as it is. However if you want the results to add to the end of the previous one each time use
STATIC vector<string> results; instead.
Last edited on Jul 19, 2011 at 3:01am
Jul 19, 2011 at 3:01am
Topic archived. No new replies allowed.