argc和argv在main函数中的应用,及unistd.h

来源:互联网 发布:淘宝联盟定金返佣 编辑:程序博客网 时间:2024/06/06 00:01
       argc,argv 用命令行编译程序时有用。
  主函数main中变量(int argc,char *argv[ ])的含义
  我们平时定义主函数时通常的写法为:int main( )或void main( )
  其实,int main( ) 只是 UNIX 及 Linux 默许的用法,
  main(int argc, char *argv[ ], char *env[ ])才是UNIX和Linux中的标准写法。
  argc: 整数,用来统计你运行程序时送给main函数的命令行参数的个数
  * argv: 字符串数组,用来存放指向你的字符串参数的指针数组
,每一个元素指向一个参数
  argv[0] 指向程序运行的全路径名
  argv[1] 指向在DOS命令行中执行程序名后的第一个字符串
  argv[2] 指向执行程序名后的第二个字符串
  argv[argc]为NULL。
  *env:字符串数组。env[ ]的每一个元素都包含ENVVAR=value形式的字符
  串。其中ENVVAR为环境变量,value 为ENVVAR的对应值。
  argc, argv,env是在main( )函数之前被赋值的,编译器生成的可执行文件,main( )不是真正的入口点,而是一个标准的函数,这个函数名与具体的操作系统有关。
  经典小例子,对于理解argv[ ]函数很管用:
  #include <stdio.h>
  int main(int argc, char *argv[ ])
{
  printf("%d\n",argc);
  while(argc)
  printf("%s\n",argv[--argc]);
  return 0;
}
  假设将其编译为test.exe
  在命令行下
  〉test hello
  得到的输出结果为
  2
  hello
  test
  main(int argc, char*argv[ ]),其中argc是指变量的个数,本例中即指test和hello(注意,命令test也算在内)这两个变量,argc即为2
  argv是一个char *的数组,其中存放指向参数变量的指针,此处argv[0]指向test,argv[1]指向hello
  再例:
  #include<unistd.h>
  #include<stdio.h>
  int main(int argc,char *argv[ ])
  {
  if(argc==1 || argc>2)
  {printf("请输入想要编辑的文件名如:fillname");}
  if(argc==2) { printf("编辑 %s\n",argv[1]); }
  exit(0)
  }
  编译该程序:gcc -o edit edit.c
  运行:〉edit
  结果:请输入想要编辑的文件名如:fillname
  运行:〉edit f1.txt
  结果:编辑 f1.txt
  执行edit时,argc为1,argv[0]指向edit
  而执行edit f1.txt时,argc的值为2,argv[0]指向edit,argv[1]指向f1.txt

unistd.h 的功能:
百度解释:
unistd.h
是 C 和 C++ 程序设计语言中提供对 POSIX 操作系统 API 的访问功能的头文件的名称。该头文件由 POSIX.1 标准(单一UNIX规范的基础)提出,故所有遵循该标准的操作系统和编译器均应提供该头文件(如 Unix 的所有官方版本,包括Mac OS X、Linux 等)。
Wiki解释:

API(Application Programming Interface,应用程序编程接口)
API(Application Programming Interface,应用程序编程接口)是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力,而又无需访问源码,或理解内部工作机制的细节。

In computer programming, an application programming interface (API) is a set ofroutines, protocols, and tools for building software and applications.

An API expresses a software component in terms of its operations, inputs, outputs, and underlying types, defining functionalities that are independent of their respective implementations, which allows definitions and implementations to vary without compromising the interface. A good API makes it easier to develop a program by providing all the building blocks, which are then put together by the programmer.


0 0
原创粉丝点击