我想知道爲什麼optarg
在下列情況下返回無效路徑:--foo=~/.bashrc
但如果我在--foo ~/.bashrc
之間留有空格,則不能。在C中使用getopt_long無效的文件路徑
什麼是解決方法,所以它適用於這兩種情況。
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
int main(int argc, char *argv[]) {
int opt = 0;
int long_index = 0;
char *f;
static struct option longopt[] = {
{"foo", required_argument, 0, 'd' },
{0,0,0,0}
};
while ((opt = getopt_long(argc, argv,"d:", longopt, &long_index)) != -1) {
switch (opt) {
case 'd' :
printf("\n%s\n", optarg);
f = realpath (optarg, NULL);
if (f) printf("%s\n", f);
break;
default:
exit(1);
}
}
return 0;
}
輸出:
$ ./a.out --foo=~/.bashrc
~/.bashrc
$ ./a.out --foo ~/.bashrc
/home/user/.bashrc
這是一個shell擴展的問題。在程序本身啓動之前,以〜開始的參數被擴展到主目錄。因爲--foo =〜/ .bashrc是單個參數,並且不以〜開頭,所以在這裏不執行擴展。 – Marian
謝謝。所以我猜這個shell無法擴展它,因爲它認爲'=〜/ .bashrc'是路徑。你知道這是否是所有炮彈中的已知問題? – user1024718
它將'--foo =〜/ .bashrc'視爲不以〜開頭的單個參數。但是,必須有一種方法來教bash在'='之後擴展'〜',因爲它正在爲'dd'命令做正確的擴展。例如'dd if =〜/ xxx'被展開。這是bash社區的問題。 – Marian