如何在“系统”中包含字符串变量(char *)命令 - linux [英] How to include a string variable(char *) within "system" command - linux
问题描述
char * S =hello; //假设它是正确动态分配的
我想在下面的语句中使用S,当S被视为值为hello的字符串时。
system(grep S searchtext.txt> result.txt);
我该怎么做?
传统上,您使用将命令行字符串格式化为缓冲区:
char buf [1024];
snprintf(buf,sizeof(buf),grep'%s'searchtext.txt> result.txt,S);
系统(buf);
当然,出于安全原因,如果 S
来自外部来源,例如文件,数据库或用户自己。这可能会导致注入shell代码。
char * S = "hello"; // assume it's dynamically allocated correctly
I want to use S in the below statement when S would be treated as a string with the value "hello".
system("grep S searchtext.txt > result.txt");
How do I do this?
In plain C, you traditionally use snprintf() to format your command line string into a buffer:
char buf[1024];
snprintf(buf, sizeof(buf), "grep '%s' searchtext.txt > result.txt", S);
system(buf);
Of course, for security reasons, you should never do that if S
comes from an external source such as a file, a database, or the user himself. That could lead to shell code injection.
这篇关于如何在“系统”中包含字符串变量(char *)命令 - linux的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!