How to use C code variable inside system()

Viewed 80

I am using C code with sed. I want to read lines in the interval 1-10,11-20 etc. to perform some calculation.

int i,j,m,n;
for(i=0;i<10;i++){
   j=i+1;
   //correction. m,n is modified which was incorrect earlier.
   m=i*10;
   n=j*10;
   system("sed -n 'm,n p' oldfile > newfile");
   }

Ouput.

  m,n p

It looks the variable is not passed in system. Is there any way to do that?

2 Answers

Use sprintf to build the command line:

char cmdline[100];
sprintf(cmdline, "sed -n '%d,%dp'  oldfile.txt > newfile.txt", 10*i+1, 10*(i+1));
puts(cmdline); // optionally, verify manually it's going to do the right thing
system(cmdline);

(This is vulnerable to buffer overflow, but if your command-line arguments are not too flexible, 100 bytes should be enough.)

You cannot replace part of a string literal in C. What you need is to

  • Form a string with patterns
  • Replace those patterns with proper values with formatted I/O functions.

sprintf()/snprintf() will be your friend in this. You can do something like (copying from pmg's comment)

char cmd[100]; 
snprintf(cmd, 100, "sed -n '%d,%dp'  oldfile > newfile", 10*i+1, 10*(i+1)); 
system(cmd);
Related