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 general it's a very very bad idea to use system
like this. system
runs the command through the shell, meaning that the string you pass to system
is subject to all of the shell's variable expansion, command expansion, special character interpretation, etc.
If you insist on using system
, you must first sanitize your string. The easiest way to do that is:
char *tmp = malloc(4*strlen(S)+3);
tmp[0] = '\'';
for (i=0,j=1; tmp[j]=S[i]; i++, j++)
if (S[i]=='\'') tmp[++j]='\\', tmp[++j]='\'', tmp[++j]='\'';
tmp[j++] = '\'';
tmp[j++] = 0;
if (snprintf(cmd, sizeof cmd, "foo %s ...", tmp) >= sizeof cmd) goto error;
system(cmd);
This code single-quotes the whole string S
and replaces any embedded single-quotes with '\''
. Note that I also checked for command line truncation in case it could lead to execution of dangerous commands.
A better alternative would be to abandon system
entirely and perform your own fork
and exec
to bypass the shell. Then there is no command line to be interpreted; you have full control over the arguments (*argv[]
array) that are passed to the external program.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With