0
下面的C代碼工作正常,但我怎麼知道用戶是否已通過選項-d或不?如何知道特定的optarg選項是否通過c
從下面的代碼,我就能知道,只有當用戶使用OPTARG -d選項
Eg : ./application -d
才把此代碼的工作!
如果用戶輸入
./application -a
然後,我不知道,如果-d選項通過與否。
而且選項-a應該採取多個值,但下面的代碼只對單次價值
eg : ./application -a knn , lr , ln
我怎樣才能使這個代碼接受相同的選項多個值嗎?
下面的代碼工作正常單值
eg : ./application -a knn
int main(int argc, char *argv[]) {
int opt= 0;
int start = -1, end = -1;
char *alg,*dir,*graph;
//Specifying the expected options
//The two options s and e expect numbers as argument
static struct option long_options[] = {
{"start",no_argument,0,'s' },
{"end",no_argument,0,'e' },
{"algorithm",no_argument, 0,'a' },
{"directory",required_argument, 0,'d' },
{"graph",required_argument,0,'g' },
{0,0,0,0}
};
int long_index =0;
int i=0,j=0;
size_t size = 1;
while ((opt = getopt_long(argc, argv,"s:e:a:d:h:g:",
long_options, &long_index)) != -1) {
switch (opt) {
case 'd' :
dir = optarg;
if (optarg == NULL)
printf("d option is must");
else
{
printf("option -d value is must\n");
usage();
exit(EXIT_FAILURE);
}
break;
case '?':
if (optopt == ('d' || 'a' || 'g' || 's' || 'e'))
fprintf (stderr, "Option -%c reqd", optopt);
usage();
exit(EXIT_FAILURE);
case 'a' :
alg = optarg;
if(alg == "lr" || alg == "knn" || alg == "cart")
{
printf("you entered option -a \"%s\"\n",optarg);
}
else
{
printf("Wrong option -a value is passed\n");
:
:
:
如果(0 == strnlen(argv的[I]中, 「-d」,2)),你能解釋這種燒焦字符串,以便列表代碼行? – programmer
@programmer,'strlen()'的手冊頁有一個非常好的解釋,但是,爲了簡單起見,比較'argv [i]'指向的char數組的前2個字節與字符串「-d」如果它們匹配,則輸入'if()'的主體 – user3629249