我正在使用此代码提取受密码保护的RAR文件.我正在使用该std::system()函数来调用RAR命令.如果我password在std::system()函数中使用它,它的工作原理.但是,当尝试将密码作为参数传递时,它不会.例如,如果在此代码中,如果我使用密码pwd,则会出现此错误:
"pwd不被识别为内部或外部命令,可操作程序或批处理文件."
但是,如果我更改代码并使其成功system("rar e -ppwd wingen.rar"),它就可以工作.
任何人都可以解释我犯的错误吗?提前致谢!
这是我的代码:
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char **argv)
{
char pword[20];
printf("enter the pword : ");
gets(pword);
system(("rar e -p%s wingen.rar",pword));
getchar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Nik*_*chi 18
system()只需要一个参数 - a const char*.事实上,
system( "rar e -p%s wingen.rar", pword );
Run Code Online (Sandbox Code Playgroud)
不会编译 - 编译器会抱怨你传递了太多的参数system().原因是:
system( "rar e -p%s wingen.rar", pword );
Run Code Online (Sandbox Code Playgroud)
compiles是你在括号中包裹了两个字符串.这具有评估内部表达式的效果,该表达式由对两个字符串进行操作的逗号运算符组成.逗号运算符具有返回第二个参数的值的效果,因此您最终调用:
system( pword );
Run Code Online (Sandbox Code Playgroud)
在您的示例中,相当于:
system( "pwd" );
Run Code Online (Sandbox Code Playgroud)
而pwd不是你的系统上的命令(虽然在POSIX系统中,......但我离题).您想要做的事情已在其他答案中解释,但为了完整性我也会提到它 - 您需要使用sprintf以下格式设置字符串格式:
char buff[256];
sprintf( buff, "rar e -p%s wingen.rar", pword );
Run Code Online (Sandbox Code Playgroud)
或者你可以连接字符串,这可能会快一点(虽然对于这么短的字符串,它可能不会有所作为):
char buff[256] = "rar e -p";
strcat( buff, pword );
strcat( buff, " wingen.rar" );
Run Code Online (Sandbox Code Playgroud)
该系统()函数接收的字符串作为参数.
它的原型是:
int system(const char *command);
Run Code Online (Sandbox Code Playgroud)
在传递之前构建字符串.也许使用snprintf().
char buf[512];
snprintf(buf, sizeof(buf), "rar e -p%s wingen.rar", pword);
system(buf);
Run Code Online (Sandbox Code Playgroud)
编辑:
所有这些解决方案都是糟糕的想法,因为使用具有未消毒输入的系统存在注入漏洞.
即使他使用snprintf我的答案,或者strcat喜欢另一个,仍然存在问题,因为system()(至少/bin/sh在*nix系统上)可以通过单个函数调用执行多个命令.
system("rar e -pXX wingen.rar ; rm -rf * ; # wingen.rar")
Run Code Online (Sandbox Code Playgroud)
将产生于:
pwd = "XX wingen.rar ; rm -rf * ; #"
Run Code Online (Sandbox Code Playgroud)
该system()函数不能像一样工作printf()。您需要创建完整的字符串,然后调用system():
char command[100];
sprintf(command, "rar e -p%s wingen.rar", pword);
system(command);
Run Code Online (Sandbox Code Playgroud)
您现在拥有的代码正在使用逗号运算符,这将导致您的“格式字符串”被程序完全忽略。您所拥有的相当于写作的100%:
system(pword);
Run Code Online (Sandbox Code Playgroud)
大概不是您想要的。
| 归档时间: |
|
| 查看次数: |
4250 次 |
| 最近记录: |