Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

command

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?

like image 535
Real Red. Avatar asked Dec 13 '22 02:12

Real Red.


1 Answers

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.

like image 79
sharptooth Avatar answered May 19 '23 07:05

sharptooth