如何在 system() 中使用 C 代码变量

How to use C code variable inside system()

我在 sed 中使用 C 代码。我想读取间隔 1-10,11-20 等中的行来执行一些计算。

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

输出。

  m,n p

看起来变量没有在系统中传递。有什么办法吗?

使用sprintf构建命令行:

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

(这容易受到缓冲区溢出的影响,但如果您的命令行参数不太灵活,100 个字节应该足够了。)

您不能在 C 中替换字符串文字的一部分。您需要的是

  • 用模式组成一个字符串
  • 用格式化的 I/O 函数用适当的值替换那些模式。

sprintf()/snprintf() 将成为您的朋友。你可以做类似的事情(从 pmg 的评论中复制)

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