C++/exe

Advertisement


Question
Hi,

How are you? I was wondering if I could bother you with the following question:

There is a compiled command line program (available for both Windows and Linux: http://www.fourmilab.ch/random/) that I execute like this:

"ent.exe -b -t input.txt"

Here the file "input.txt" is simply a text file containing 1's and 0's, one value per line.

Now I'd like to run this program from within my C++ code. I know there is "system" command that could be used like this:
system("ent.exe -b -t input.txt"). However, the tricky part is reading the ent program's output so that my own program could continue using it. I'd like to read it into a string that I could then parse. This is the part that I don't know. I'd be very thankful if you could help me with this a little bit.

If you have time, maybe you could also comment on how the same works on Linux. What replaces the "system" command in Linux?

Regards,
Andres

Answer
The simplest way (which would work identically on both Windows and POSIX) would be to redirect stdout of the program to a file, and then read the file in your program. Something like:

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <iterator>
using namespace std ;

int main()
{
       system( "ent.exe -b -t input.txt > output.txt" ) ;
       ifstream file( "output.txt" ) ;
       std::istreambuf_iterator<char> begin(file), end ;
       std::string output_of_program( begin, end ) ;
       std::cout << output_of_program << '\n' ;
}

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.