2013-11-02 32 views
0

所以我知道你可以使用getopt()來查找選項參數,但是argv數組中的其他內容如目標呢?有沒有辦法做到這一點使用getopt()?通過手冊頁看,我什麼也沒有看到......也許我錯過了它。使用getopt()查找目標

+1

'argv'中的目標是什麼?也許可以考慮(在Linux上)[argp函數](http://www.gnu.org/software/libc/manual/html_node/Argp.html) –

+1

您可以詳細說明您的「目標」嗎? –

+0

我在下面的評論中解釋了第一個答案。 – user2079802

回答

2

使用optarg表示(它是一個字符串,使用sscanf來讀取它)。

man 3 getopt報價:

optstring is a string containing the legitimate option characters. If such a character is followed by a colon, the option requires an argument, so getopt() 
    places a pointer to the following text in the same argv-element, or the text of the following argv-element, in optarg. Two colons mean an option takes an 
    optional arg; if there is text in the current argv-element (i.e., in the same word as the option name itself, for example, "-oarg"), then it is returned in 
    optarg, otherwise optarg is set to zero. This is a GNU extension. If optstring contains W followed by a semicolon, then -W foo is treated as the long 
    option --foo. (The -W option is reserved by POSIX.2 for implementation extensions.) This behavior is a GNU extension, not available with libraries before 
    glibc 2. 

如果你有額外的參數(點菜cp -l file1 file2)它們保留在argv最新的位置,從optind

PS:在man頁面末尾還有一個示例。

+0

沒錯,但我不知道如何告訴getopt()來查找這些參數。現在我以這種方式調用getopt:'getopt(argc,argv,「f:j:」)'所以我告訴它首先查找'-f'選項並返回參數,然後它執行相同的操作爲'-j'選項。但是如果我有一個額外的字符串需要解析,而且它之前沒有'-f'或'-j'說明符,那又如何呢? – user2079802

+0

它會留在'argv'中,你可以從那裏讀取它。所有不匹配的選項都留在那裏。 –