getopt()는 명령줄 옵션을 사용하는 데 사용되는 내장 C 함수 중 하나입니다. 이 함수의 구문은 다음과 같습니다 -
getopt(int argc, char *const argv[], const char *optstring)
opstring은 문자 목록입니다. 각각은 단일 문자 옵션을 나타냅니다.
이 함수는 많은 값을 반환합니다. 다음과 같습니다 -
- 옵션이 값을 취하는 경우 해당 값은 optarg에 의해 지정됩니다.
- 더 이상 처리할 옵션이 없으면 -1을 반환합니다.
- 인식할 수 없는 옵션임을 나타내기 위해 '?'를 반환하고 optopt에 저장합니다.
- 때때로 일부 옵션에는 값이 필요합니다. 옵션이 있지만 값이 없으면 '?'도 반환됩니다. optstring의 첫 번째 문자로 ':'를 사용할 수 있으므로 값이 지정되지 않으면 '?' 대신 ':'를 반환합니다.
예시
#include <stdio.h>
#include <unistd.h>
main(int argc, char *argv[]) {
int option;
// put ':' at the starting of the string so compiler can distinguish between '?' and ':'
while((option = getopt(argc, argv, ":if:lrx")) != -1){ //get option from the getopt() method
switch(option){
//For option i, r, l, print that these are options
case 'i':
case 'l':
case 'r':
printf("Given Option: %c\n", option);
break;
case 'f': //here f is used for some file name
printf("Given File: %s\n", optarg);
break;
case ':':
printf("option needs a value\n");
break;
case '?': //used for some unknown options
printf("unknown option: %c\n", optopt);
break;
}
}
for(; optind < argc; optind++){ //when some extra arguments are passed
printf("Given extra arguments: %s\n", argv[optind]);
}
} 출력
Given Option: i Given File: test_file.c Given Option: l Given Option: r Given extra arguments: hello