在代码测试过程中,发现如果执行的命令参数中包含特殊字符,如单引号、空格等时,命令无法正确执行。比如在c代码中调用system语句执行zip压缩命令,文件绝对路径为/home/hui/abc .txt,文件名中包含空格,具体测试代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include<sys/types.h>
int main(void) {
char * file_name;
char *zip_name;
char command[1024];
memset(command, 0, sizeof(command));
file_name = "/home/hui/abc .txt";
zip_name = "/home/hui/abc .txt.zip";
sprintf(command, "%s%s%s%s", "zip -r ", zip_name, " ", file_name);
printf("Command is:%s\n",command);
int ravl= system(command);
printf("%d\n", ravl);
return EXIT_SUCCESS;
}
编译执行之后可以发现,出现如下错误:
为此,在shell终端中执行相同命令,使用tab按键对文件名进行自动补充,发现正确命令如下:
由此可知,shell命令中对于空格之类的特殊字符需要引用转义字符。
解决方法:
经过测试,通过对包含特殊字符的路径使用双引号进行处理,则可以方便有效的解决问题。shell测试如下:
修改程序如下,则可成功执行。
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include<sys/types.h>
int main(void) {
char * file_name;
char *zip_name;
char command[1024];
memset(command, 0, sizeof(command));
file_name = "\"/home/hui/abc .txt\"";//此处进行了修改
zip_name = "\"/home/hui/abc .txt.zip\"";//此处进行了修改
sprintf(command, "%s%s%s%s", "zip -r ", zip_name, " ", file_name);
printf("Command is:%s\n",command);
int ravl= system(command);
printf("%d\n", ravl);
return EXIT_SUCCESS;
}
执行结果如下:
需要注意的是,仅在调用shell命令时需要对包含特殊字符的路径参数进行加引号处理。对于函数库中的stat、open等函数中的路径不需要进行处理,可以直接识别。