Question

I want to access variable of c in system command but i do not know how to do it i tried like below but this does not works

#include<stdlib.h>
int main(){
int a=12;
system("echo $a");
}
Was it helpful?

Solution

You can't do this via any kind of string interpolation such as you've tried. What you need to do is build the command string before passing it to system().

#include <stdio.h>
#include <stdlib.h>

int main() {
    int a = 12;
    char command[100];
    sprintf(command, "echo %d", a);
    system(command);
}

OTHER TIPS

The system function takes a const char* argument and returns an integer value depending on the system; usually its the status code of the command after being executed.

int system (const char* command);

So to embed variables from your c program you'd have to build a command string and then pass it to system(); Apart from using sprintf() as suggested above you can use string functions such as strcat() as well to build complex commands from your C variables. For example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int a = 12;
    char command[] = "ls";
    char opt[] = " -l";
    char cmd[50];
    strcat(command, opt);

    sprintf(cmd, " | head -n %d", a);

    strcat(command, cmd);
    printf("%s\n", command );
    int rv = system(command);
    printf("Return value : %d\n", rv);

    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top