[Linux] 명령어 Option 추출 함수 (getopt)
프로그램을 작성 할 때 option 활용은 많이 요구된다. 이 때 linux에선 이를 위한 함수를 제공한다.
getopt
해당 함수는 “-“가 붙은 option에 대해서만 추출해준다.
getopt optstring parameters getopt [options] [--] optstring parameters getopt [options] -o|--options optstring [options] [--] parameters #Example getopt (argument count, argument string, "option 종류")
| Return | Description |
|---|---|
| -1 외 다른 값 | getopt 인자로 넣은 option에 해당하는 문자를 출력 |
| -1 | 더 이상 받아 올 문자가 없을 시 |
# Example
while (ch = getopt(argc, argv, "al") != -1)
printf("%c ", ch);
Example
좀 더 세련된 코드를 작성한다면 아래처럼 작성 가능하다.
#include <stdio.h>
#include <unistd.h>
#define A_FLAG (1<<0)
#define B_FLAG (1<<1)
#define C_FLAG (1<<2)
int main( int argc, char **argv ) {
int i;
int ch;
int flag = 0;
while( (ch = getopt( argc, argv, "alh")) != -1 ) {
switch(ch) {
case 'a' : flag |= A_FLAG; break; // 0001
case 'l' : flag |= B_FLAG; break; // 0010
case 'h' : flag |= C_FLAG; break; // 0100
}
}
if(flag & A_FLAG)
printf("a option\n");
if(flag & B_FLAG)
printf("l option\n");
if(flag & C_FLAG)
printf("h option\n");
return 0;
}