簡體   English   中英

如果有錯誤命令行參數,如何使getopt_long()不打印?

[英]How to make getopt_long() print nothing when there is error command-line arguments?

我有一個程序使用getopt_get()來解析命令行參數。 我的代碼是這樣的:

int opt;
int optionIndex;
static struct option longOptions[] = {
    {"help", no_argument, NULL, 'h'},
    {"test", no_argument, NULL, 't'},
    {0, 0, 0, 0}
}; 
while ((opt = getopt_long(argc, argv, "ht", longOptions, &optionIndex)) != -1) {
    switch (opt) {
        case 'h':
            help();
            return 0;
            break;
        case 't':
            init();
            test();
            return 0;
            break;
        case '?':
            help();
            return 1;
            break;
        default:
            printf("default.\n");
    }   

當我將正確的命令行參數傳遞給程序時,它運行良好。 但是當錯誤的參數傳遞給程序時,它會打印出像這樣煩人且多余的單詞。

例如,我將錯誤的參數'q'傳遞給程序

$ ./program -q
./program: invalid option -- 'q'
Usage: -h -t

當有錯誤的參數時,我只想讓它運行我的函數help()而不打印任何單詞。

./program: invalid option -- 'q'

如何停止getopt_long打印這個煩人的單詞並且什么都不打印?

閱讀精細手冊 ......

如果getopt()無法識別選項字符,它會向stderr輸出一條錯誤消息,將該字符存儲在optopt中 ,並返回“?”。 調用程序可以通過將opterr設置為0來防止錯誤消息。

所以,在調用getopt_long之前嘗試這個:

opterr = 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM