Reputation: 21817
Suppose I do a system("ps-C nautilus");
how do I return the result of this function in char* ?
Thank you.
Upvotes: 1
Views: 759
Reputation: 7939
If your compiler supports some variant of popen() you can redirect the output fairly easily.
Caveats:
char *RunProg(const char *szCmdLine) { size_t nSize=512; size_t nUsed=0; char *szOut = malloc(nSize); FILE *fp = _popen(szCmdLine, "r"); char szBuff[128]; while( !feof( fp ) ) { if( fgets( szBuff, sizeof(szBuff), fp ) != NULL ) { nUsed += strlen(szBuff); if (nUsed >= nSize) { nSize += nUsed; szOut = realloc(szOut, nSize); } strcat(szOut, szBuff); } } _pclose(fp); return szOut; }
Upvotes: 1
Reputation: 7939
The simplest solution is probably something like this:
system("ps-C nautilus > /tmp/data.txt");
then open the file and read in the contents.
Update Obviously you would not use a hard-coded file name. In the above code I was just illustrating the technique. There are many ways to ensure that your file name is unique.
Upvotes: -1
Reputation: 20236
You don't. Not sure what platform you're on, but have a look at the popen
function instead. You'll get a bidirectional pipe this way, which you can do file operations on, like reading to get a string out of it.
Upvotes: 7