系统();不允许我传递变量

system(); not allowing me to pass in variables

我正在尝试做一些可以在一个命令中编译和运行 .c 文件的东西。但我遇到了问题。我通过 get_string(); 得到了文件名;在_cs50.h_图书馆下。

现在我要给 system() 函数这个命令 make {filename} 这样做

system("make %s", filename")

但它只是返回这个错误:

mac.c:18:23: error: too many arguments to function call, expected single argument '__command', have 2 arguments
    system("make %s", filename);
    ~~~~~~            ^~~~~~~~

我明白这意味着 system() 函数有太多参数,但我不知道在 make 之后添加文件名的任何其他方法。

这是我正在使用的代码的副本,如果您需要进一步查看它。谢谢! Click Here to go to the github page 如果您找到修复程序,请对其进行评论,或者您可以在 github!

上提出拉取请求

system() 只接受一个参数。您需要预先构建字符串,然后将其传递给已经构建的字符串。

为此,您可能正在寻找类似 sprintf().

的函数

出现该编译错误是因为 system() 只需要一个字符串参数。

如果您需要使命令依赖于参数,请先使用 sprintf:

构建它
char command[256];

sprintf(command, "make %250s", filename);
system (command);

%250s 格式是为了避免在 filename 超过 250 个字符的不太可能的情况下,我们 超出范围 of command数组.

允许限制总长度的更安全的函数是snprintf:

snprintf(command, 255, "make %s", filename);