Harsha
Harsha

Reputation: 343

How should I pass variable to system() C call?

How should I call System C call if I want to send echo $c > 1.txt? I was able to send c to 1.txt but how can I send $c (in script sense) in C code (i.e., the value in c)?

My code is something like this:

void main() {
    int c =100;
    system("echo c > 1.txt");
}

I would like to save 100 in the file 1.txt

Upvotes: 0

Views: 443

Answers (3)

webminal.org
webminal.org

Reputation: 47316

Using fopen/fwrite/fclose is the proper. But If you want to use shell code then something like below will work:

int main(){
    int c =100;
    char cmd_to_run[256]={'\0'};
    sprintf(cmd_to_run,"echo %d > 1.txt",c);
    system(cmd_to_run);
}

Upvotes: 0

syntagma
syntagma

Reputation: 24354

You should use the sprintf() function to construct appropriate command and then pass it to your system() call:

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

int main() {
    int c = 100;
    char buffer[128];
    sprintf(buffer, "echo %d > 1.txt", c);
    system(buffer);
    return 0;
}

Upvotes: 2

Weather Vane
Weather Vane

Reputation: 34583

If you really want to use a system call you can do it like this - prepare the system string first:

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

int main(void) {
    char str[42];
    int c = 100;
    sprintf(str, "echo %d > 1.txt", c);
    system(str);
    return 0;
}

... but a way to do it in C is like this:

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

int main(void) {
    int c = 100;
    FILE *fil;
    fil = fopen("1.txt", "wt");
    if(fil != NULL) {
        fprintf(fil, "%d", c);
        fclose(fil);
    }
    return 0;
}

Upvotes: 0

Related Questions