C ++执行CMD命令 [英] C++ Executing CMD Commands
问题描述
我在这里遇到严重问题。我需要通过C ++执行CMD命令行而不显示控制台窗口。因此,由于窗口将显示,因此我不能使用 system(cmd)
。
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.
我尝试了 winExec(cmd,SW_HIDE)
,但这也不起作用。 CreateProcess
是我尝试过的另一个。但是,这是用于运行程序或批处理文件的。
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.
我最终尝试了 ShellExecute
:
ShellExecute( NULL, "open",
"cmd.exe",
"ipconfig > myfile.txt",
"c:\projects\b",
SW_SHOWNORMAL
);
有人可以看到上面的代码有问题吗?我一直使用 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 :)
推荐答案
将输出重定向到您自己的管道是一个更整洁的解决方案,因为它避免了创建输出文件,但这可以正常工作:
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);
您没有看到cmd窗口,并且输出已按预期重定向。
You don't see the cmd window and the output is redirected as expected.
您的代码可能失败了(除了 / C
外),因为您将路径指定为 c :\projects\b
而不是 c:\\projects\\b
。
Your code is probably failing (apart from the /C
thing) because you specify the path as "c:\projects\b"
rather than "c:\\projects\\b"
.
这篇关于C ++执行CMD命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!