※ 이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.
프로그램 실행시 입력 받은 인자를 받아 분석하여 옵션 처리를 가능케 해주는 함수 입니다.
extern char * optarg : 인수를 필요로 하는 옵션을 처리할 때 필요한 인수 포인터
: 인자를 필요로 하는 옵션에 대한 인자값이 optarg에 들어가 있다.
extern int optind : 처리되는 인자의 숫자를 나타낸다.
#./exe -a -b -c -d 123 -e
1 2 3 4 5 6 7 <--- optind
extern int opterr : 에러 문자열 출력 여부를 결정한다. (0 이면 출력 안한다.)
extern int optopt : 지정되지 않은 옵션을 저장하는 변수
추가 설명
옵션만 사용하고 싶을때
함수 사용법 : while( (c=getopt(argc, argc, "a")) != -1)
명령어 실행 : #./getoptTest -a
옵션에 인자를 집어 넣고 싶을때
함수 사용법 : while( (c=getopt(argc, argc, "a:")) != -1)
명령어 실행 : #./getoptTest -a abc
위의 두가지를 다 쓰고 싶을 때
함수 사용법 : while( (c=getopt(argc, argc, ":a:")) != -1)
명령어 실행 : #./getoptTest -a
명령어 실행 : #./getoptTest -a abc
":a:" 이부분에서 맨앞에 : 이것을 빼게되면 a: 이것만 남게 되는데 이때는 인자 값이 없다면 오류를 발생하게 된다.
":a:"와 같이 쓰면 인자를 넣어도 되고 안 넣어두 된다. 하지만 인자값이 없다면 case 'a'를 실행 하는 것이 아니라 case ':'를 실행하므로 처리는 따로 해주어야 한다.
없는 옵션을 실행하게 되면 case '?'가 실행된다.
사용 예제 )
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int c;
extern char *optarg;
extern int optind;
printf("Current Option Number: %d\n",optind);
while( (c=getopt(argc, argv, ":abc:d:")) != -1) {
switch(c) {
case 'a':
printf("Option : a");
break;
case 'b':
printf("Option : b");
break;
case 'c':
printf("Option : c, Argument : %s",optarg);
break;
case 'd':
printf("Option : d, Argument : %s",optarg);
case ':':
if(optopt=='c') printf("ccc");
if(optopt=='a') printf("aaa");
if(optopt=='b') printf("bbb");
if(optopt=='d') printf("ddd");
break;
case '?':
printf("Option Error!! No Option : %c",optopt);
break;
}
printf("\tNext Option Number : %d\n",optind);
}
return 0;
}
'프로그래밍 언어' 카테고리의 다른 글
[C] 배열 초기화 방법 (0) | 2014.08.11 |
---|---|
[C] __attribute__((packed)); 사용 하는 이유 (0) | 2014.08.11 |
[C] Linux C connect() 함수 (0) | 2014.08.07 |
[C] Linux C close() 함수 (0) | 2014.08.07 |
[C] Linux C write() 함수 (0) | 2014.08.07 |