본문 바로가기
엔지니어/IT창고

[Linux-C] getopt 의 이해 및 사용

by Kyolee. 2019. 11. 27.
반응형

[Linux-C] getopt 의 이해 및 사용

Qiita의 getopt 사용법에 관한 포스팅을 번역하였습니다. Reference Link 는 본 포스팅의 가장 아래에 표시하였습니다. 

 

오늘은 Linux C 환경에서 사용하는 getopt 에 대해서 학습해 보기로 한다. getopt 는 main 함수의 argc, argv 를 해석하는 것으로, 이때 문자열인 argv[1] ~ argv[argc-1]를 argument list 라고도 한다. 

위키피디아에 따르면 getopt는 command-line option 을 분석하는 데 사용되는 C라이브러리 함수라고 정의된다. 그렇다면 command-line option이 무엇인지 알아보자. 

option

Option이란 아래와 같이 Linux 에서 ‘-‘ 로 시작하는 문자열을 의미한다. 

$./getopt -a
$./getopt -b optarg
$./getopt -b optarg nonopt 

즉, ‘-a‘, ‘-b‘ 가 option 이고, ‘-‘의 뒤에 오는 ‘a‘와 ‘b‘는 option character 라고 부른다. 

이 때, option은 option argument를 지정할 수 있는데, 바로 두 번째 예시에서의 -b의 뒤에 오는 optarg가 option argument이다. 그리고, option에도 option-argument에도 포함되지 않는 argument-list의 요소를 non-option argument(nonopt)라고 부른다. 

 

optstring

optstirng은 option character를 나타내는 문자열이다. 

const char* opstring = "ab:";

여기에서도 ab는 option character이고, 뒤에 오는 ‘-b‘는 ‘:‘를 이용하여 option-argument를표시한다.

 

$./command -a         # OK
$./command -a bbb   # OK bbb is non-option argument
$./command -accc     # Error
$./command -abbb    # OK b is treated as '-b', bb is option argument
$./command -b         # Error option requires an argument
$./command -b bbb   # OK bbb is option argument
$./command -bbbb    # OK bbb is option argument
$./command -c         # error 

 

optarg

getopt가 option argument를 갖는 option을 해석하면, optarg에 option argument를 가리키는 포인터가 설정된다. 즉, optarg를 참조하는 것으로 option argument를 취할 수 있다.

 

optind

optind는 getopt가 다음에 처리할 argv 배열의 index로, 초기값은 1로 설정되어 있다. 그래서 최초의 호출은 argv[1]부터 해석을 시작한다. index = 1 으로 설정함으로써 여러번 argv[1]로 해석을 실행할 수 있다. 

 

opterr

opterr은 error log의 출력을 제어한다. 

opterr가 0이 아닐 때 error log가 출력되고, 0이면 error log가 출력되지 않는다. 

 

optopt

에러가 발생한 option character를 보유한다. 

 

getopt의 처리 

getopt의 처리가 완료되면 option character를 리턴하고, option-argument가 존재하면 optarg에 설정한다. 

에러가 발생하면 ?‘ 을 리턴한다.

 

* Error 발생의 원인 

  - ‘-‘ 로 시작하는 문자열이지만 option character가 없는 경우

  - option-argument를 갖는 option이지만 option-character가 없는 경우 

 

다음으로 처리할 option이 없어진 경우, -1을 리턴한다. 

-1 을 리턴한 후 optind에는 non-option argument가 있으면 그것을 표시하고, 없으면 argc와 일치시킨다. 

 

 

 

https://qiita.com/tobira-code/items/24e583c30f07c4853f8f

반응형

댓글