Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables to system function in C [duplicate]

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! :)

like image 365
AnaBanana Avatar asked May 18 '15 14:05

AnaBanana


2 Answers

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);                                                               
}  
like image 140
Ôrel Avatar answered Nov 01 '22 09:11

Ôrel


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.

like image 24
Werner Henze Avatar answered Nov 01 '22 10:11

Werner Henze