要使用system(command),您需要将command 字符串与命令行参数中的选项连接 构建成单个字符串。例如,如果您想使用system() 将所有参数作为参数传递给/usr/bin/gkbroot,则需要声明一个足够大的缓冲区(字符数组)以容纳"/usr/bin/gkbroot",并在每个参数和nul 终止 字符。
您可以通过将缓冲区初始化为"/usr/bin/gkbroot",然后循环遍历每个参数,添加space,然后将参数添加到缓冲区(在验证command 缓冲区中存在足够的存储空间之后)。例如:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXC 1024 /* if you need a constant, #define one (or more) */
int main (int argc, char **argv) {
char command[MAXC] = "/usr/bin/gkbroot";
size_t len = strlen (command);
for (int i = 1; i < argc; i++) {
size_t arglen = strlen (argv[i]);
if (len + arglen + 2 > MAXC) {
fputs ("error: arguments exceed command storage.\n", stderr);
return 1;
}
strcat (command, " ");
strcat (command, argv[i]);
len += arglen + 1;
}
printf ("system (%s)\n", command);
// system (command);
}
(注意:实际的system(command);当前已被注释掉。要执行实际的命令,请取消注释该行)
使用/输出示例
$ ./bin/system_command TRYNEW /etc/cron.d ./grill/mk
system (/usr/bin/gkbroot TRYNEW /etc/cron.d ./grill/mk)
无论您提供多少参数,只要它们适合command,这将起作用,例如
$ ./bin/system_command arg1 arg2 arg3 arg4 arg5 arg6
system (/usr/bin/gkbroot arg1 arg2 arg3 arg4 arg5 arg6)
让我知道这是否是您的意图,如果您还有其他问题。