如何使用可变参数调用系统命令 [英] how to call system command with variable parameters
问题描述
您好,
我正在寻找一种在Window环境中使用可变参数调用系统命令的方法
。
类似于system(),但我需要
才能传递可变参数。
我试过这个:
系统(命令 - %s - %s,参数1,参数2);
这个
Hello,
I'm looking for a way to call system commands with variable parameters
within a Window environment.
Sort of like system() but i need to be
able to pass variable parameters.
I tried this:
system("command -%s -%s", parameter1, parameter2);
and this
char buffer[200];
string p="192.168.1.100";
sprintf(buffer,"ping %s",p);
system(buffer);
system("pause");
然而,我仍然会收到错误。
有人可以指导我,我做错了吗?
最好的问候,
Victor
However, i still get error.
Can someone direct me, what i am doing wrong?
Best Regards,
Victor
推荐答案
您的代码的问题在于您传递了std :: string
到sprintf
,如果一个人出现并用板球拍扯它,就不会知道字符串是什么。我建议使用stringstream
格式化字符串而不是sprintf
- 没有缓冲区溢出的可能性。
一旦你掌握了执行下一个有趣部分的命令就会得到结果...
The problem with your code is that you're passing astd::string
tosprintf
, which wouldn't know what a string was if one came up and twatted it with a cricket bat. I'd suggest using astringstream
to format the string rather thansprintf
- there's no chance of a buffer overflow.
Once you've got the command to execute the next fun-part is getting the results back...
你的例子代码没问题,将执行ping命令。但是,如果参数包含空格,引号或特定保留字符,则必须用引号括起这些参数。要保存,您还应该用引号括起完整的命令。您的ping示例将如下所示:
Your example code is OK and will execute the ping command. But if your parameters contain spaces, quotes or specific reserved characters, you must enclose these parameters by quotes. To be on the save side, you should also enclose the complete command by quotes. Your ping example would then look like this:
sprintf(buffer,"\"ping \"%s\"\"",p);
为了使它更复杂,当参数本身被双引号字符括起来时,还有另一种特殊情况。然后它必须被另一对引号括起来。
system()
函数将命令运行为' cmd / c命令'。您可以打开命令shell并执行'help cmd'以获取有关引用的一些信息。
To make it more complicated, there is another special case when a parameter itself is enclosed by double quote characters. Then it must be enclosed by another pair of quotes.
The system()
functions runs the command as 'cmd /c command'. You can open a command shell and execute 'help cmd' to get some information on quoting.
您好,
首先,感谢您的帮助和快速反应。
中学,Jochen Arndt我按照你的说法做了但我收到的错误如下:
Ping请求找不到主机d_↕。请检查姓名,然后重试。
按任意键继续。 。 。
最好的问候,
Victor
Hello,
First of all, thank you for your help and quick response.
Secondary, Jochen Arndt I did as you told me but I am getting the error below:
Ping request could not find host d_↕. Please check the name and try again.
Press any key to continue . . .
Best Regards,
Victor
这篇关于如何使用可变参数调用系统命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!