获取gcc getopt示例来接受长参数?

时间:2014-04-07 10:43:17

标签: c gcc getopt-long

我试图让以下code使用命令

rectangle –area –length 12 –breadth 34

但是我收到了错误

rectangle: invalid option -- r

使用短参数选项

rectangle -a -l 12 -b 34

我得到了正确的答案

Area: 408

代码:

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

/** Program to calculate the area and perimeter of 
 * a rectangle using command line arguments
 */
void print_usage() {
    printf("Usage: rectangle [ap] -l num -b num\n");
}

int main(int argc, char *argv[]) {
    int opt= 0;
    int area = -1, perimeter = -1, breadth = -1, length =-1;

    //Specifying the expected options
    //The two options l and b expect numbers as argument
    static struct option long_options[] = {
        {"area",      no_argument,       0,  'a' },
        {"perimeter", no_argument,       0,  'p' },
        {"length",    required_argument, 0,  'l' },
        {"breadth",   required_argument, 0,  'b' },
        {0,           0,                 0,  0   }
    };

    int long_index =0;
    while ((opt = getopt_long(argc, argv,"apl:b:", 
                   long_options, &long_index )) != -1) {
        switch (opt) {
             case 'a' : area = 0;
                 break;
             case 'p' : perimeter = 0;
                 break;
             case 'l' : length = atoi(optarg); 
                 break;
             case 'b' : breadth = atoi(optarg);
                 break;
             default: print_usage(); 
                 exit(EXIT_FAILURE);
        }
    }
    if (length == -1 || breadth ==-1) {
        print_usage();
        exit(EXIT_FAILURE);
    }

    // Calculate the area
    if (area == 0) {
        area = length * breadth;
        printf("Area: %d\n",area);
    }

    // Calculate the perimeter
    if (perimeter == 0) {
        perimeter = 2 * (length + breadth);
        printf("Perimeter: %d\n",perimeter);
    }
    return 0;
}

1 个答案:

答案 0 :(得分:2)

长选项必须以--而不是-为前缀。

所以

rectangle –-area –-length 12 –-breadth 34

应该有用。

<强>更新

另外,可以使用以下表格:

rectangle –-area –-length=12 –-breadth=34

您可能希望通过更改以下内容来更正使用声明:

printf("Usage: rectangle [ap] -l num -b num\n");

printf("Usage: rectangle [-a|--area -p|--perimeter] -l|--length num -b|--breadth num\n");