2

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

2 Answers 2

8

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.