How to read / redirect the output of a dos command to a program variable in C / C ++?

I want to run the dos command from my program, for example, the "dir" command. I do it like:

system("dir"); 

Is there a way to read the output of this command directly to a program variable?

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

And then reading the command.out file. But how can we do this directly, rather than redirecting to a file and then reading?

+4
source share
5 answers

Found an alternative way, or rather, the equivalent of a popen window. This is _popen (). This only works for me, and in addition, it is easy to use.

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

Find details with a complete example here .

+4
source

You cannot redirect it to a variable, but you can do a trick similar to how pipes are used in Unix to chain commands. Call CreateProcess() and pass it an instance of STARTUPINFO with the appropriate set of descriptors and STARTF_USESTDHANDLES in STARTUPINFO::dwFlags . Then read the data coming from the spawned process through the given descriptors.

+4
source

If your library has a POSIX popen() function, this is what you need. You can read the output of the command from the channel and analyze it in any way.

 FILE *dir; char direntry[80]; dir = popen("dir", "r"); while (!feof(dir)) { fgets(direntry, sizeof(direntry), dir); /* do something with direntry */ } 
+4
source

You can not. Programs work in different memory spaces, as these are different processes. As a rule, in modern operating systems, processes do not exchange memory.

In addition, it would be difficult to define a variable in C that might contain the output of a command such as "dir"; he must grow dynamically to make room.

It is best to use a pipe that allows you to read the output of a command from a stream from which you can save it as you see fit.

+1
source

Use popen (), it does exactly what you want.
He creates a bi-directional tube, unfolds the processes. In the child case, it connects the pipe to standard and standard, and then executes 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"; } 
0
source

All Articles