0

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

syntagma
  • 20,485
  • 13
  • 66
  • 121
Vrajendra
  • 303
  • 1
  • 12
  • `echo \$c`? you're firing up a shell, which means shell metachars have to be taken into account. – Marc B Aug 26 '16 at 17:04
  • For the sake of explanation I gave $c as an example. 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 – Vrajendra Aug 26 '16 at 17:07
  • Use `fopen` to open a text file, `fprintf` your data, `fclose` the file. – Weather Vane Aug 26 '16 at 17:14
  • 1
    [`void main()` is incorrect](http://stackoverflow.com/q/204476/995714) and is a relic from a pre-standard C compiler – phuclv Aug 26 '16 at 17:19
  • 1
    So your question is *How do I write the value of a variable to a file?* instead. You should [edit] to make it clear that's what you're asking (after searching here to see if it's been asked before, of course). You don't *echo* from within an application; that's for use at the command line. You also don't need `system()` here. – Ken White Aug 26 '16 at 17:22

3 Answers3

2

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;
}
syntagma
  • 20,485
  • 13
  • 66
  • 121
0

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);
}
webminal.org
  • 37,814
  • 34
  • 84
  • 122
0

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;
}
Weather Vane
  • 31,226
  • 6
  • 28
  • 47