Passing variables to system function in C [duplica

2020-04-12 02:57发布

问题:

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

回答1:

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


回答2:

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.



回答3:

The System function doesnt have the formatting options like printf, instead the system function takes a C string as a parameter.

Check out the following site for more info.

http://www.tutorialspoint.com/c_standard_library/c_function_system.htm