如何正确使用 system() 在 C++ 中执行命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6672257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to properly use system() to execute a command in C++?
提问by ash
I am new to C++ programming under Windows. I am trying to execute a command say cuobjdump
in C++ code using the system()
function:
我是 Windows 下 C++ 编程的新手。我正在尝试cuobjdump
使用以下system()
函数在 C++ 代码中执行一个命令:
system("C:\program files\nvidia gpu computing...\cuobjdump.exe --dump-cubin C:\..\input.exe");
output:
输出:
Usage : cuobjdump [options] <file>
This followed by the list of the options for cuobjdump.
接下来是 cuobjdump 的选项列表。
When I execute this program I always get the cuobjdump help options displayed in the command line. It's as if the system call does not parse the filename. What am I doing wrong? I get the same result while using createprocess. The options --dump-cubin
gives an error as if I mistyped it.
当我执行这个程序时,我总是得到命令行中显示的 cuobjdump 帮助选项。就好像系统调用不解析文件名一样。我究竟做错了什么?我在使用 createprocess 时得到相同的结果。这些选项--dump-cubin
给出了一个错误,就好像我打错了一样。
采纳答案by Grzegorz Szpetkowski
Give a try with (that is, surrounding cuobjdump.exe path with "
, properly escaped in C++ as \"
):
尝试使用(即,用 包围 cuobjdump.exe 路径"
,在 C++ 中正确转义为\"
):
system("\"C:\program files\nvidia gpu computing...\cuobjdump.exe\" --dump-cubin C:\..\input.exe");
回答by Ben Voigt
system("cuobjdump --dump-cubin path\filename.exe");
system("cuobjdump --dump-cubin path\filename.exe");
That \f
is interpreted by the compiler as a string escape sequence, try path\\filename.exe
这\f
是由编译器作为一个字符串转义序列解释,尝试path\\filename.exe
回答by geekosaur
Most obviously, \
is an escape character in C / C++ strings, so it has to be doubled if you want to use it literally.
最明显的是,它\
是 C/C++ 字符串中的转义字符,所以如果你想按字面意思使用它,它必须加倍。
system("cuobjdump --dump-cubin path\filename.exe");
回答by Diego Sevilla
Assuming that path
is correct, you have to use a double \\
within strings to represent a single \
.
假设这path
是正确的,您必须\\
在字符串中使用 double来表示单个\
.
回答by Ajay
I suggest you to use CreateProcess, or ShellExecute/ ShellExecuteExsince you are working on Windows. system
and ShellExecute
eventually calls CreateProcess
only.
我建议您使用CreateProcess或ShellExecute/ ShellExecuteEx,因为您在 Windows 上工作。system
并ShellExecute
最终CreateProcess
只调用。