C C++ 命令行参数

来源:互联网 发布:plc触摸屏编程 编辑:程序博客网 时间:2024/05/29 14:19
可以通过在程序的main()函数中添加形式参数来接收程序在启动时从命令行中获得的各个命令行参数,包括:程序名称、路径、当前环境变量和用户指定参数等。命令行参数由启动程序截获并传递给main()。
一个典型的命令行例子如:
Mycopy srcFile destFile
一个典型的main()例子如:
int main( int argc, char *argv[ ] , char *envp[ ]  );
argc
指示数组指针argv中包含的参数个数,该整数总是大于等于1。
argv
一个以NULL以为的字符串数组,存储用户输入的命令行参数。按照惯例,argv[0]为程序调用的命令,如c:/mycopy.exe;argv[1]为第一个命令行参数,直到argv[argc-1];argv[argc]总是NULL。
envp
存储执行当前程序的用户环境变量
#include<stdio.h>
int main(int argCount,char * argValue[], char * envp[])
{
 FILE* srcFile = 0, *destFile =0;
 int ch = 0;
 int i = 0;
 if (argCount != 3){
       printf("Usage:%s src-file-name dest-file-name/n",argValue[0]);
 }else{
       if((srcFile = fopen(argValue[1],"r")) == 0){
       printf("Can not open source file/"%s/"!",argValue[1]);
 }else{
       if((destFile = fopen(argValue[2],"w")) ==0){
              printf("Can not open destination file/"%s/"!",argValue[2]);
       }else{
              while((ch = fgetc(srcFile))!= EOF) fputc(ch,destFile);
              printf("Successful to copy a file!/n");
              fclose(srcFile);
              fclose(destFile);
              printf("%d command line parameters are got in program /n",argCount);
              printf("All command line parameters are list here:/n");
              while(envp[i]!=NULL){
              printf("%s/n",argValue[i]);   
              i++;
              }
              i = 0;
printf("The variable set is list here:/n");
              while(envp[i]!=NULL){
              printf("%s/n",envp[i]);   
              i++;
              }
              return 0;
              }
       }
 }
 return 1;
}
 
原创粉丝点击