0
getopt()のoptargパラメータを使用して引数パラメータを処理しようとしていますが、nullのままです。これはc99標準と関係がありますか?実際にoptargから文字列をコピーする必要があることはわかっていますが、決して設定されません。getopt()からのoptargは常にNULLです
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>
int main(int argc, char *argv[]) {
char *optarg;
int ch;
char *indir = NULL;
while ((ch = getopt(argc, argv, "d:")) != -1) {
switch(ch) {
case 'd':
indir = optarg;
fprintf(stderr, "Optarg: %s\n", optarg);
fprintf(stderr, "Dir name: %s\n", indir);
break;
default :
fprintf(stderr, "Usage: test -d <input directory>\n");
exit(1);
}
}
if(indir == NULL){
fprintf(stderr, "Input directory required.\n");
exit(1);
}
else{
printf("Input dir: %s\n", indir);
}
return 0;
}
'char * optarg;' – BLUEPIXY
wowを削除してください。ありがとうございました! @BLUEPIXY – DAnsermino
この重要な文を含む 'getopt()'のマニュアルページを読むべきです: 'オプション文字がもうない場合、getopt()は-1を返します。次にoptindは、オプションではない最初のargv要素のargvのインデックスです。 ' – user3629249