C语言argv[]与argc各有什么作用

如题

argc与argv[]是启动C程序时系统传入的,可以直接使用。argc是参数数量,argv是参数表数组。如命令行为“prg.exe 1 2 3”,则argc为4,argv[0]="prg.exe",argv[1]="1",argv[2]="2",argv[3]="3"。以下是LCC-WIN32模板文件(加了一行显示所有参数语句):
/* --- The following code comes from e:\lcc\lib\wizard\textmode.tpl. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void Usage(char *programName)
{
fprintf(stderr,"%s usage:\n",programName);
/* Modify here to add your usage message when the program is
* called without arguments */
}

/* returns the index of the first argument that is not an option; i.e.
does not start with a dash or a slash
*/
int HandleOptions(int argc,char *argv[])
{
int i,firstnonoption=0;

for (i=1; i< argc;i++) {
if (argv[i][0] == '/' || argv[i][0] == '-') {
switch (argv[i][1]) {
/* An argument -? means help is requested */
case '?':
Usage(argv[0]);
break;
case 'h':
case 'H':
if (!stricmp(argv[i]+1,"help")) {
Usage(argv[0]);
break;
}
/* If the option -h means anything else
* in your application add code here
* Note: this falls through to the default
* to print an "unknow option" message
*/
/* add your option switches here */
default:
fprintf(stderr,"unknown option %s\n",argv[i]);
break;
}
}
else {
firstnonoption = i;
break;
}
}
return firstnonoption;
}

int main(int argc,char *argv[])
{
if (argc == 1) {
/* If no arguments we call the Usage routine and exit */
Usage(argv[0]);
return 1;
}
/* handle the program options */
HandleOptions(argc,argv);
/* The code of your application goes here */

for (int i=0;i<argc;i++)printf("%s ",argv[i]);

return 0;
}
温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网