命令行参数处理

http://www.ibm.com/developerworks/cn/aix/library/au-unix-getopt.html

http://hi.baidu.com/harite/blog/item/2ad9aaec43f87b3d2697913d.html

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>

struct Student
{
    int id;          
    char *name;      
};

//  optSting是选项参数组成的字符串,
//  字符后跟一个冒号,表明该选项要求有参数。
static const char *optString = "i:n:h?";

//  option结构称为长选项表,其声明如下:
//struct option {           //  四个域分别是
//    const char *name;     //  --长指令
//    int has_arg;          //  required_argument 1:带参数     no_argument       0:不带参数
//    int *flag;            //  NULL
//    int val;              //  -短指令
//};    
//  option结构数组,最后以 { NULL, no_argument, NULL, 0} 结束

static const struct option longOpts[] = {
    { "id", required_argument, NULL, 'i'},
    { "name", required_argument, NULL, 'n'},
    { "help", no_argument, NULL, 'h'},
    { NULL, no_argument, NULL, 0}
};

void Help( void )
{
    puts( "Help: \n  not help~" );
    exit( EXIT_FAILURE );
}

int main( int argc, char *argv[] )
{
    struct Student boy = {0,NULL};

    int opt;
    while ( (opt = getopt_long(argc,argv,optString,longOpts,NULL )) != -1 )
    {
        switch ( opt )
        {
            case 'i':
                boy.id = atoi(optarg);
                break;

            case 'n':
                boy.name = optarg;
                break;

            case 'h': 
            case '?':
                Help();
                break;
            default: break;
        }
    }

    printf( "id: %d\n", boy.id );
    printf( "name: %s\n", boy.name );

    return EXIT_SUCCESS;
}



你可能感兴趣的:(html,c,unix,IBM,AIX)