I have this C code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
printf("Please enter a number:\n");
scanf("%d",&a);
printf("Your number is: %d\n",a);
system("echo %d",a);
}
I'm interested in the last command, the system()
function and why I can't print my variable like i printed it with printf()
. I want to be able to ask the user some input , let's say a string and then pass it to the system function.
Practical example:
Ask user for folder name
system("mkdir %s", FolderName);
Thank you in advance! :)
Use snprintf
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
char buf[BUFSIZ];
printf("Please enter a number:\n");
scanf("%d",&a);
printf("Your number is: %d\n",a);
snprintf(buf, sizeof(buf), "echo %d",a);
system(buf);
}
system
, unlike printf
does not accept multiple parameters, it only accepts one parameter, a const char *command
. So you need to build your complete command string first in memory and then pass it to system.
An example would be:
char buf[32];
sprintf(buf, "echo %d", a);
system(buf);
You need to take care not to write more chars into buf than buf has space for. You might want to read the man page for snprintf
to rewrite the code in a safer way.
Also: if your code really compiled, then please compile with a higher warning level. At least that would have given you warnings that you are calling system with more parameters than you should.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With