2015年1月13日 星期二

[C] Program Long Arguments 1


#include <stdio.h>
#include <unistd.h>
#define _GNU_SOURCE
#include <getopt.h>

struct option longopts[] = {
{"initialize", 0, NULL, 'i'},
{"file", 1, NULL, 'f'},
{"list", 0, NULL, 'l'},
{"restart", 0, NULL, 'r'},
{0,0,0,0}};

int main(int argc, char *argv[])
{
int opt;

while((opt = getopt_long(argc, argv, "if:lr", longopts, NULL)) != -1) {
        switch(opt) {
        case 'i':
        case 'l':
        case 'r':
        printf("option: %c\n", opt);
        break;
        case 'f':
        printf("filename: %s\n", optarg);
        break;
        case ':':
        printf("option needs a value\n");
        break;
        case '?':
        printf("unknown option: %c\n", optopt);
        break;
    }
}

for(; optind < argc; optind++)
    printf("argument: %s\n", argv[optind]);
    exit(0);
}

./a.out --init --l --file fred.c ‘hi there’
option: i
option: l
filename: fred.c
argument: ‘hi
argument: there’

or

./a.out --init --l --file=fred.c ‘hi there’
option: i
option: l
filename: fred.c
argument: ‘hi
argument: there’

Reference:
  • [Book] Beginning Linux Programming 3rd

0 意見:

張貼留言