Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using the output from PIPE / System() 1

Status
Not open for further replies.

evosix

Programmer
Apr 27, 2003
9
AU
Hi,

What im trying to do is:
Put the output of a system command (eg: ls) into a variable in C++.

ATM, what im doing is putting the output of the system command into a file, then reading from it.
>> system("ls > blah.dat");

Is there a way to put the output into a variable??
eg: >> system(&quot;ls > <variable>&quot;);

I am wanting to do this with child/ren processes, so does that mean the variable should always be different to avoid being writted over by different processes??

thanks in advance,

-evosix-
 
Have you considered using [tt]popen[/tt] instead, which gives you a [tt]FILE *[/tt] directly?

//Daniel
 
Thankyou daniel once again.
you rock :)

-evosix
 
(youmight consider giving our rocking daniel a star ? ;))

Greetz,
muppeteer.gif


NOSPAM_themuppeteer@hotmail.com (for mails, remove the NOSPAM_)

&quot;Those who say they understand chess, understand nothing&quot;

-- Robert HUBNER
 
More over, file i/o isn't that difficult. declare an fstream and read the data in (for this popen, or a file function instead of a system call is prefered).

Code:
#include <fstream>
#include <string>
main()
{
   ifstream fin;//declare file in stream
   string s = &quot;&quot;;//place to put stuff we get.
   fin.open(blah.dat);
   if(!fin.bad())//make sure there isn't a I/O error
   {
     getline(fin, s, '\n');//read file (including spaces)
     //up to the new line char
     cout << s;//print it
   }
   else
   {
    cerr << &quot;Problem opening blah.dat,&quot;;
    cerr << &quot;check to see it exsists&quot; <<endl;
    return 1;
   }
   return 0;
}

How ever, because of the external program popen is best.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top