c - C:getopt无法识别选项。有人可以解释吗?

标签 c arguments option getopt

我必须写一个程序,可以从一个讲座的选项开始,但是
似乎选项'-r'不起作用。
我可以编译它,没有任何错误或警告,但如果我要启动它,
它告诉我'-r'是一个非选项,这将由开关盒块后的for循环引起。
CLI - Compile - Run

#include <pthread.h>    /* used for threading */
#include <stdio.h>
#include <unistd.h>     
#include <ctype.h>      /* used for isprint() function */
#include <stdlib.h>     /* used for lrand48, labs, strtol etc. */
#include <time.h>       /* used for clock and etc */
#include <assert.h>     /* used for assert function */


int rflag = 0;      /* Flag for min size (rand) */
int Rflag = 0;      /* Flag for max size (rand) */
int rvalue = 0;     /* Defualt min size */
int Rvalue = 100;   /* Default max size */
int vflag = 0;      /* Flag for  verbose output */
extern const char *gitversion;

void *PrintHello(void *threadarg) {
    /******************************************************
    * - print in one line the Thread Number given in threadarg 
    *   and "Hello World" 
    * - sleep a random time (see line below!)
    ******************************************************/
    pthread_t tid = pthread_self();     /* The Thread Id of the current thread */
    int num = *((int*) threadarg);          /* Number of the Thread */

    long sleeping_time = (lrand48() % (Rvalue - rvalue + 1) + rvalue);
    if (sleeping_time < 0) {
        sleeping_time = labs(sleeping_time);
    }
    printf("Hello everybody, I'm thread number %d\n", num);
    if (vflag == 1) {
        printf("The Thread ID of Thread number %d is = %lu.\n", num, tid);
    }
    sleep(sleeping_time);
    /* say goodbye */       
    printf("%d: Thread is done after sleeping %ld[s]\n", num, sleeping_time);

    return(NULL); /* Dummy to make -Wall happy ... */
}

/*
 * Prints a little help to stdout
 */
void printHelp() {
    printf("------------------------------HELP--------------------------------\n");
    printf("Usage: [Option] [Argument(If required!)]\n\n");
    printf("Option '-h' - Prints this Help and the current GIT Revision\n");
    printf("Option '-v' - Prints more Informations corresponds to 'verbose'\n");
    printf("Option '-t' - Requiers a number as Argument which represents the\n");
    printf("              Number of Thread which will be created\n"); 
    printf("Option '-r' - Minimum Randomsize\n");
    printf("Option '-R' - Maximum Randomsize\n");
    printf("------------------------------------------------------------------\n");
    printf("Git Revision #:  %s\n", gitversion);
    printf("------------------------------------------------------------------\n");
}


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

    void *status;
    long t;
    int hflag = 0;
    int tflag = 0;
    long NumberOfThreads = 4;
    int c;
    int i;

    while((c = getopt(argc, argv, "ht:vr:R:")) != -1) {
        switch(c) {
            case 'h':
                hflag = 1;
                break;
            case 't':
                tflag = 1;
                NumberOfThreads = strtol(optarg, NULL, 10);
                /*assert(NumberOfThreads != 0);*/
                break;
            case 'v': 
                vflag = 1;
                break;
            case 'r':
                rflag = 1;
                rvalue = strtol(optarg, NULL, 10);
                if (rvalue < 0) {
                    fprintf(stderr, "The number has to be greater than zero!\n");
                    exit(-1);
                }
                break;
            case 'R':
                Rflag = 1;
                Rvalue = strtol(optarg, NULL, 10);
                if (Rvalue < 0) {
                    fprintf(stderr, "The number has to be greater than zero!\n");
                    exit(-1);
                } else if (Rvalue < rvalue) {
                    fprintf(stderr, "The max number for rand has to be greater than the min number!\n");
                    exit(-1);
                }
                break;
            case '?':
                if (optopt == 't') {
                    fprintf(stderr, "Option -%c requires an argument!\n", optopt);
                } else if (optopt == 'r') {
                    fprintf(stderr, "Option -%c requires an argument!\n", optopt);
                } else if (optopt == 'R') {
                    fprintf(stderr, "Option -%c requires an argument!\n", optopt);
                } else if (isprint(optopt)) {
                    fprintf(stderr, "Unknow Option -%c!\n", optopt);
                } else {
                    fprintf(stderr, "Unknown Option character '\\x%x'!\n", optopt);
                }
                return -1;
            default:
                fprintf(stderr, "Something did go wrong. Please use '-h' for help!\n");
        }    
        for (i = optind; i < argc; i++) {
            fprintf(stderr, "Non-option argument %s!\n", argv[i]);
            exit(-1);
        }
    }

    if (hflag == 1 && tflag == 0) {
        printHelp();
        exit(0);
    } else if (hflag == 1) {
        printHelp();
    }

    /*******************************************
    * Initialise thread attributes here        *
    *******************************************/
    pthread_t threads[NumberOfThreads];
    long thread_args[NumberOfThreads];
    int check_code;

    /* 
     * Create Threads
     */
    for (t = 0; t < NumberOfThreads; t++) {
        thread_args[t] = t;
        printf("Creating thread %ld\n", t);
        check_code = pthread_create(&threads[t], NULL, PrintHello, (void*) &thread_args[t]);
        /* Check if everything gone right */
        assert(check_code == 0);
        /* verbose output */
        if (vflag == 1) {
            printf("Thread %ld is creted and will do his job now!\n", t);
        }
    }
    for (t = 0; t < NumberOfThreads; t++) {
        check_code = pthread_join(threads[t], &status);
        assert(check_code == 0);
        printf("Main joining with thread %ld\n", t);
        if (vflag == 1) {
            printf("Completed joining with thread %ld status = %d\n", t, (int) status);
        }
    }
    return (0);
}

最佳答案

显示for值的Non-option循环位于调用whilegetopt()循环内。移动它,使其位于包含对while调用的getopt()循环之后。
现在,您的while循环看到第一个选项,然后在处理完所有选项之前处理for循环。

关于c - C:getopt无法识别选项。有人可以解释吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36958321/

相关文章:

c - 缓冲区溢出与环境变量

python - 在 Python 中编写一个 'print' 函数

f# - F# 中是否有标准选项工作流?

python - 根据配置选项的Python铃声

'auto-closed' 括号的 Vim 插件?

c - 如何测试四子棋胜利条件?

c - 读取大小无效 - 查找命令行平均值

c - 增加字符串值的数字末尾

PHP 匿名函数作为默认参数?

c - 使用指针传递结构数组时遇到问题