tags:

views:

50

answers:

1

While I try the following:

system( "ifconfig -a | grep inet | "
          "sed 's/\\([ ]*[^ ]*\\)\\([ ]*[^ ]*\\).*$/\\1 \\2/' "
          " > address.txt" ) ;

I am getting the output in a file. How can I assign the out put to a variable.

+1  A: 

EDIT: the best way to do this as recommended in @Paul R's comment, is to use _popen and read in the command output from stdin. There is sample code at that MSDN page.

ORIGINAL EFFORT:

One option would be to create a temp file using tmpnam_s, write your output there instead of hard-coding the filename, and then read it back from the file into a std::string,deleting the temp file once you are done. Based on the MSDN sample code:

#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <sstream>

int main( void )
{   
   char name1[L_tmpnam_s];
   errno_t err;

   err = tmpnam_s( name1, L_tmpnam_s );
   if (err)
   {
      printf("Error occurred creating unique filename.\n");
      exit(1);
   }
   stringstream command;
   command << "ifconfig -a | grep inet | " <<
          "sed 's/\\([ ]*[^ ]*\\)\\([ ]*[^ ]*\\).*$/\\1 \\2/' " <<
          " > " << (const char*)name1;
   system(command.str().c_str());

  {
     ifstream resultFile((const char*)name1);
     string resultStr;
     resultFile >> resultStr;

     cout << resultStr;
  }
  ::remove(name1);
}

This code uses the CRT more than I would usually, but you seem to have a methodology you wish to use that relies on this.

Steve Townsend