【问题标题】:How to execute an executable with argument from within C program?如何从 C 程序中执行带有参数的可执行文件?
【发布时间】:2018-05-31 23:56:21
【问题描述】:

int s = system("./my_prog 32"); 有效,但是如何将参数作为变量引入? int a = 32; int s = ("system %d", a); 似乎不起作用(“函数‘系统’的参数太多”。)

【问题讨论】:

  • 使用sprintf 创建字符串。
  • snprintf 几乎总是比sprintf 更好。
  • @aschepler 为什么?因为缓冲区溢出?

标签: c system


【解决方案1】:

C 中的 system() 函数采用 const char * 类型的单个参数。这就是您的第一个示例有效的原因(尽管您的第二个示例格式错误)。

不过,您可以使用stdio.h 中的sprintf() 函数来实现您想要的。 int a = 32; char command[80]; sprintf(command, "./my_prog %d", a); system(command);

【讨论】:

  • @John Bollinger 击败我。 :)
【解决方案2】:

如何将参数作为变量引入?

一种常见的技术是动态生成命令字符串,使用sprintf()。例如:

char command[100];
int a = 42;
sprintf(command, "./my_prog %d", a);
int s = system(command);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 2014-12-17
    相关资源
    最近更新 更多