Al Smith
Al Smith

Reputation: 253

How can I merge strings in the system function?

I have some string, foo and I want to be able to run something like as foo.s -o foo.o. If this were printf, I would be able to do printf("as %s.s -o %s.o", foo, foo);. What I want to be able to do is something like that, except with the system function. How can I do this? Using the same approach as printf gives me an error saying I've passed too many arguments.

In my code, I have:

   for (int i = 1; i < argc; i++) {
     system("as %s.s -o %s.o", *(argv + i), *(argv + i));
   }

But this gives me an error saying I have too many arguments. I suppose I could go through the painful process of looping through character arrays, but I'd rather avoid that.

Upvotes: 4

Views: 96

Answers (1)

Stargateur
Stargateur

Reputation: 26727

You could use snprintf():

int size = snprintf(NULL, 0, "as %s.s -o %s.o", argv[i], argv[i]);
if (size < 0) {
  return ERROR; // handle error as you like
}
char *p = malloc(++size); // we add the +1 for the nul terminate byte
if (p == NULL) {
  return ERROR;
}
int ret = snprintf(p, size, "as %s.s -o %s.o", argv[i], argv[i]);
if (ret < 0) {
  free(p);
  return ERROR;
}

system(p);

free(p); // if you don't need it anymore

Note: The only problem is that for obscure reason, snprintf() don't return size_t. But it's the only fonction we can use in std to do what you want.

Upvotes: 5

Related Questions