C语言教程:命令行参数

2018-10-1307:51:55编程语言入门到精通Comments3,110 views字数 1490阅读模式

从命令行传递的参数称为命令行参数。这些参数由main()函数来处理的。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6622.html

要支持命令行参数,您需要更改main()函数的结构,如下所示 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6622.html

int main(int argc, char *argv[] )
C

在这里,argc计算参数的数量。它将文件名称作为第一个参数。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6622.html

argv []包含参数的总数。第一个参数永远是此程序的文件名。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6622.html

命令行参数实例

我们来看一下命令行参数的例子,用文件名传递一个参数。创建一个源文件:main-commandline.c,其代码如下所示 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6622.html

#include <stdio.h>  
void main(int argc, char *argv[] )  {  
   printf("Program name is: %s\n", argv[0]);  
   if(argc < 2){  
      printf("No argument passed through command line.\n");  
   }
   else{  
      printf("First argument is: %s\n", argv[1]);  
   }
}
C

在Linux上执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6622.html

root@AYZ:~#  gcc main-commandline.c
root@AYZ:~#  ./a.out argc_value
Program name is: ./a.out
First argument is: argc_value
Shell

在Windows中从命令行运行以下程序:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6622.html

F:\>cd worksp\clanguage\command-line-arguments\Debug

F:\worksp\clanguage\command-line-arguments\Debug>dir
 驱动器 F 中的卷是 Others
 卷的序列号是 0007-6F29

 F:\worksp\clanguage\command-line-arguments\Debug 的目录

2017/08/18  01:23    <DIR>          .
2017/08/18  01:23    <DIR>          ..
2017/08/18  01:23            37,376 command-line-arguments.exe
2017/08/18  01:23           291,652 command-line-arguments.ilk
2017/08/18  01:23           552,960 command-line-arguments.pdb
               3 个文件        881,988 字节
               2 个目录 53,178,052,608 可用字节

F:\worksp\clanguage\command-line-arguments\Debug>command-line-arguments.exe test-arg
Program name is: command-line-arguments.exe
First argument is: test-arg

F:\worksp\clanguage\command-line-arguments\Debug>
Shell

如果传递很多参数,它只会打印一个,如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6622.html

root@AYZ:~# ./a.out hello I am Maxsu
Program name is: ./a.out
First argument is: hello
Shell

但是,如果您在双引号内传递许多参数,则所有参数将被视为单个参数。如下 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6622.html

root@AYZ:~# ./a.out "hello I am Maxsu"
Program name is: ./a.out
First argument is: hello I am Maxsu
Shell

您可以编写程序来打印所有参数。在这个程序中,我们只打印argv [1],这就是为什么只打印一个参数的原因了,您可以根据需要使用或打印argv [2],argv [3],argv [4]....等等。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/6622.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/6622.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定