Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Executing CMD Commands

I'm having a serious problem here. I need to execute a CMD command line via C++ without the console window displaying. Therefore I cannot use system(cmd), since the window will display.

I have tried winExec(cmd, SW_HIDE), but this does not work either. CreateProcess is another one I tried. However, this is for running programs or batch files.

I have ended up trying ShellExecute:

ShellExecute( NULL, "open",
    "cmd.exe",
    "ipconfig > myfile.txt",
    "c:\projects\b",
    SW_SHOWNORMAL
);

Can anyone see anything wrong with the above code? I have used SW_SHOWNORMAL until I know this works.

I really need some help with this. Nothing has come to light, and I have been trying for quite a while. Any advice anyone could give would be great :)

like image 582
JP29 Avatar asked Jul 19 '12 15:07

JP29


People also ask

Can C run cmd?

We usually use a compiler with a graphical user interface, to compile our C program. This can also be done by using cmd. The command prompt has a set of steps we need to perform in order to execute our program without using a GUI compiler.

How do I access C in cmd?

Change Directory in CMD to C Drive You can find it by typing “CMD” in your search bar. Enter “ cd ” or “ chdir .” Press the “Space” key. Type in “ C: ” beside “ cd ” in the CMD.


1 Answers

Redirecting the output to your own pipe is a tidier solution because it avoids creating the output file, but this works fine:

ShellExecute(0, "open", "cmd.exe", "/C ipconfig > out.txt", 0, SW_HIDE);

You don't see the cmd window and the output is redirected as expected.

Your code is probably failing (apart from the /C thing) because you specify the path as "c:\projects\b" rather than "c:\\projects\\b".

like image 73
arx Avatar answered Oct 20 '22 05:10

arx