创建一个 "template"(格式)字符串

标签 c string printf variadic-functions

我希望能够创建一个模板字符串,然后像这样使用它:

int execute_command(char *cmd) {
  //...
}

char *template_command = "some_command %s some_args %s %d";
char *actual_command = template_command % (cmd1, arg1, 123);
// error, how do I do that?
int res = execute_command(actual_command);

最佳答案

如果您知道 actual_command 的最大长度,那么您可以使用以下任一方法:

char actual_command[MAX_LEN+1];

// Option #1
sprintf(actual_command, template_command, cmd1, arg1, 123);

// Option #2
snprintf(actual_command, MAX_LEN+1, template_command, cmd1, arg1, 123);

如果 MAX_LEN 没有被正确定义,那么:

  • 选项 #1 将导致未定义的行为(可能是运行时异常)
  • 选项 #2 将产生不正确的结果(actual_command 的内容)

关于创建一个 "template"(格式)字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25831456/

相关文章:

c - 如何从 root 更改进程的真实用户 ID

c - 如何用c获取主板的uuid

c - 数组中的文件指针

Swift 3 隐式解包选项导致错误的字符串插值

c - 错误: conflicting types for 'removeSpaces'

c++ - 在 msvc 和 gcc 上使用 vsnprintf 时的不同行为

c++ - sprintf 未定义行为

c - 遍历C字符串: get the last word of a string

c++ - 错误 4 错误 C3861 : 'snprintf' : identifier not found

c - 在for循环中声明int数组并在C中更改其元素