如何在C字符串中传递包含引号的系统命令

时间:2016-12-26 16:49:01

标签: c string bash

如果已经回答道歉,但我找不到解决问题的答案。 我正在尝试在C中传递系统字符串:该命令的bash版本是

grep -w "dog\|animal" myfile

我有以下C代码:

char str[50] ="dog\\|animal";
char file[50]="myfile";
char buf[20];
snprintf(buf, sizeof(buf), "grep -w \"%s\" %s",str,file);
system(buf);

当我编译并运行它时,我收到了这个错误:

  

sh:1:语法错误:未终止的引用字符串

最小例子:

#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);
}

1 个答案:

答案 0 :(得分:1)

将评论转移到答案中。

你有两个组件字符串大小为50,并且你试图将它们挤压成一个20字节的目标。你应该使用200而不是20。

无论如何,20太短了。您有12个字符的开销加上文件名中的6个字符和匹配模式中的11个字符。这不会带来幸福。 (注意,如果你从snprintf()检查了返回,它会告诉你它需要的空间比你给它的多。)。最基本的调试技术将添加printf("[%s]\n", buf)来向您显示正在执行的内容。

#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;
}

示例输出(程序名称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
$

请注意sprintf()返回的大小不包括空终止符;缓冲区需要至少29个字节才能容纳所有内容。