【问题标题】:Linux C getopt ignore after the first unspecified argumentLinux C getopt 在第一个未指定的参数后忽略
【发布时间】:2013-11-02 22:31:15
【问题描述】:

我想让程序完成“execvp(argv[1],argv+1);”如果第一个参数未定义,但 getopt 解析所有以“-”开头的参数。如何忽略第一个未定义参数之后的所有参数?这可以使用getopt吗?目前,我有代码:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
void print_usage() {
     printf("Usage: here print usage\n");
}

int main(int argc, char *argv[]) {
    int option = 0;
char user[32]={0}, command[50]={0};
while ((option = getopt(argc, argv,"c:u:h")) != -1) {
    switch (option) {
         case 'c' : strcpy(command,optarg);
             break;
         case 'u' : strcpy(user,optarg);
             break;
         case 'h' : print_usage();
                    exit(EXIT_SUCCESS);
             break;
         default:
             print_usage();
             exit(EXIT_SUCCESS);
    }
}

if(strlen(user)!=0) {
    if (strlen(command)!=0)
        printf("execute %s for %s\n",command,user);
    else
        printf("please specify command\n");
}
else {
    if (strlen(command)!=0)
        printf("please specify user\n");
    else if (argc > 2)
         printf("execute %s for everyone\n",argv[1]);

}

return 0;

}

当你执行时,我得到:

./thisprogram ls -l
./thusprogram: invalid option -- 'l'

我想做这样的;

./thisprogram ls -l /
razem 52
lrwxrwxrwx   1 root root     7 05-31 20:40 bin -> usr/bin
drwxr-xr-x   5 root root  4096 10-21 22:44 boot
drwxr-xr-x  19 root root  3160 11-02 17:10 dev

等等……但我不知道。

【问题讨论】:

    标签: c linux getopt execvp


    【解决方案1】:

    遇到未知参数时停止解析。

    int done = 0;
    while (!done && (option = getopt(argc, argv,"c:u:h")) != -1) {
        switch (option) {
         ...
        default:
            done = 1;
            break;
       }
    }
    

    (或者,如果您愿意,可以使用 case '?': 而不是 default: 的情况,因为 getopt 在遇到未知参数时会返回 '?')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      • 2014-06-05
      相关资源
      最近更新 更多