0

I want to be able to create a template string and then use it like this:

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);
1
  • 2
    Use snprintf, and remember to allocate enough space. Use malloc for that. POSIX asnprintf does that all for you, easy to define it yourself. Commented Sep 14, 2014 at 8:29

2 Answers 2

1

If you know the maximum length of actual_command, then you can use either one of the following:

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

If MAX_LEN is not defined correctly, then:

  • Option #1 will result with undefined behavior (possibly runtime exception)
  • Option #2 will result with incorrect result (contents of actual_command)
1

Use snprintf and malloc (snprint returns the length of the string it would have written was the buffer only big enough, and receives the size of the buffer). POSIX asnprintf packages that nicely.
If you don't have it, define your own like this:

char* my_asnprintf(const char* format, ...) {
    va_list arg;
    va_start(arg, format);
    size_t n = 1 + vsnprintf((char*)format, 0, format, arg);
    va_end(arg);
    char* ret = malloc(n);
    if(!ret)
        return ret;
    va_start(arg, format);
    vsnprintf(ret, n, format, arg);
    va_end(arg);
    return ret;
}

Don't forget to free the buffer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.