Reputation: 1316
Apologies if this has been answered, but I haven't found an answer that solves my problem. I'm trying to pass a system string in C: the bash version of the command is
grep -w "dog\|animal" myfile
I have the following C code:
char str[50] ="dog\\|animal";
char file[50]="myfile";
char buf[20];
snprintf(buf, sizeof(buf), "grep -w \"%s\" %s",str,file);
system(buf);
When I compile and run it I am given this error:
sh: 1: Syntax error: Unterminated quoted string
Minimum example:
#include <stdio.h>
#include <string.h>
int main(){
char str[50] ="dog\\|animal";
char file[50]="myfile";
char buf[20];
snprintf(buf, sizeof(buf), "grep -w \"%s\" %s",str,file);
system(buf);
}
Upvotes: 0
Views: 217
Reputation: 754490
Transferring comment into answer.
You have two component strings size 50, and you try to squeeze them into a 20-byte target. You should be using perhaps 200 instead of 20.
At any rate, 20 is too short. You have 12 characters of overhead plus 6 in the file name and 11 in the match pattern. That's not going to lead to happiness. (Note that if you had checked the return from snprintf(), it would tell you it needs more space than you gave it.). And the most elementary debug technique would add printf("[%s]\n", buf)
to show you what is being executed.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[50] = "dog\\|animal";
char file[50] = "myfile";
char buf[20];
int size;
if ((size = snprintf(buf, sizeof(buf), "grep -w \"%s\" %s", str, file)) >= (int)sizeof(buf))
printf("Oops! (%d) ", size);
printf("[%s]\n", buf);
system(buf);
return 0;
}
Example output (program name sh11
):
$ ./sh11
Oops! (28) [grep -w "dog\|anima]
sh: -c: line 0: unexpected EOF while looking for matching `"'
sh: -c: line 1: syntax error: unexpected end of file
$
Note that the size returned by sprintf()
does not include the null terminator; the buffer needs to be at least 29 bytes to hold everything.
Upvotes: 1