Incerteza
Incerteza

Reputation: 34924

Create a "template" (format) string

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

Upvotes: 0

Views: 52

Answers (2)

barak manos
barak manos

Reputation: 30136

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)

Upvotes: 1

Deduplicator
Deduplicator

Reputation: 45674

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.

Upvotes: 1

Related Questions