命令行参数使用main()函数参数进行处理,其中 argc 表示传递的参数数量,而 argv [] 是指向每个传递的参数的指针数组到程序。以下是一个简单的示例,该示例检查命令行是否提供了任何参数并采取相应的措施-
#include <stdio.h> int main( int argc, char *argv[] ) { if( argc == 2 ) { printf("The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\n"); } else { printf("One argument expected.\n"); } }
当使用单个参数编译并执行以上代码时,将产生以下输出。
链接:https://www.learnfk.comhttps://www.learnfk.com/c-programming/c-command-line-arguments.html
来源:LearnFk无涯教程网
$./a.out testing The argument supplied is testing
当使用两个参数编译并执行以上代码时,将产生以下输出。
$./a.out testing1 testing2 Too many arguments supplied.
在不传递任何参数的情况下编译并执行上述代码时,将产生以下输出。
$./a.out One argument expected
应当注意, argv [0] 保存程序本身的名称,而 argv [1] 是指向所提供的第一个命令行参数的指针,而* argv [ n]是最后一个参数。如果未提供任何参数,则argc将为1,如果传递一个参数,则 argc 设置为2。
#include <stdio.h> int main( int argc, char *argv[] ) { printf("Program name %s\n", argv[0]); if( argc == 2 ) { printf("The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\n"); } else { printf("One argument expected.\n"); } }
当上面的代码使用由空格分隔但在双引号内的单个参数编译和执行时,将产生以下输出。
$./a.out "testing1 testing2" Progranm name ./a.out The argument supplied is testing1 testing2
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)