views:

1141

answers:

5

I want to run a dos command from my program for example "dir" command. I am doing it like,

system("dir");

Is there any way to read the output of that command directly into a program variable?

We can always redirect the output to a file and then read that file, by doing
system("dir > command.out");

And then reading command.out file. But how can we do it directly rather than redirectling to a file and then reading?

+4  A: 

You can't redirect it to a variable, but you can do a trick similar to how pipes are used in Unix for chaining commands. Call CreateProcess(), and pass it a STARTUPINFO instance with accordingly set handles and STARTF_USESTDHANDLES in STARTUPINFO::dwFlags. Then read the data coming from the spawned process through the set handles.

sharptooth
+1  A: 

You can't. The programs run in different memory spaces, as they are different processes. Generally, in modern operating systems, processes don't share memory.

Also, it would be difficult to define a variable in C that can hold the output of a command such as "dir"; it's would need to dynamically grow to make room.

The best way is to use a pipe, that will make it possible to read the command's output from a stream, from which you can store it as you see fit.

unwind
+4  A: 

If your library has popen() POSIX function, that's what you need. You can read command output from pipe and parse it any way you like.

FILE *dir;
char direntry[80];

dir = popen("dir", "r");
while (!feof(dir)) {
    fgets(direntry, sizeof(direntry), dir);
    /* do something with direntry */
}
qrdl
this works only on unix systems right? I mean popen() is not a part of standard c/c++. I doubt equivalent library is available popen() for use on windows.
Chandan .
It is POSIX function. There are POSIX stacks for Windows - http://en.wikipedia.org/wiki/Posix#POSIX_for_Windows
qrdl
+1  A: 

Found an alternate way or rather windows equivalent of popen. It is _popen(). This works just right for me and moreover it's easy to use.

   char   psBuffer[128];
   FILE   *pPipe;

   if( (pPipe = _popen( "dir", "rt" )) != NULL)
  {
     while(fgets(psBuffer, 128, pPipe))
     {
       printf(psBuffer);
     }
  }

Find the details with full example here.

Chandan .
This works well and is easy to use. Hence, selecting it as the answer.
Chandan .
A: 

Use popen() it does exactly what you want.
It creates a bidirectional pipe, forks the processes. In the child it then connects the pipe to standard in and standard out then execs the command specified as the first parameter to popen().

#include <stdio.h>
#include <string>
#include <iostream>

int main()
{
    std::string     output;
    FILE*           data    = popen("cat PLOP","r");

    for(char c = getc(data);c != EOF;c = getc(data))
    {
        output  += c;
    }
    pclose(data);

    std::cout << "Data(" << output << ")\n";
}
Martin York