Patrick Dennis
Patrick Dennis

Reputation: 331

How to execute an executable with argument from within C program?

int s = system("./my_prog 32"); works, but how do I bring in the argument as a variable? int a = 32; int s = ("system %d", a); doesn't seem to work ("too many arguments to function 'system' ".)

Upvotes: 1

Views: 65

Answers (2)

jdc
jdc

Reputation: 732

The system() function in C takes a single argument of type const char *. That is why your first example works (though, your second example is malformed).

Still, what you want can be achieved using the sprintf() function in stdio.h. int a = 32; char command[80]; sprintf(command, "./my_prog %d", a); system(command);

Upvotes: 2

John Bollinger
John Bollinger

Reputation: 180093

how do I bring in the argument as a variable?

A common technique is to generate the command string dynamically, with sprintf(). For example:

char command[100];
int a = 42;
sprintf(command, "./my_prog %d", a);
int s = system(command);

Upvotes: 1

Related Questions