0xAX
0xAX

Reputation: 21817

return result of system function in char*

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

Answers (3)

Michael J
Michael J

Reputation: 7939

If your compiler supports some variant of popen() you can redirect the output fairly easily.

Caveats:

  1. The code below was written on a Windows box, which uses _popen() instead of popen(). It is not hard to convert for *nix.
  2. The code below has no error handling. It is just intended to illustrate the technique. You must add error checking before using it in production.
  3. This all runs in one thread. If the program was likely to run for a long time, you might need to use a second thread to read its output while it runs.
  4. I think popen() is POSIX, which means it will work on most *nix boxes, but it is not standard C, so should not be considered portable.
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

Michael J
Michael J

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

jer
jer

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

Related Questions