본문 바로가기

C/C++

C 옵션 처리 라이브러리 - getopt

@markdown

# C 옵션 처리 라이브러리 - getopt


Linux의 glibc에서는 `getopt`라는 commandline argument parser 라이브러리를 기본적으로 제공하고 있다.

아쉽게도 C 표준은 아니기 때문에, 크로스 플랫폼은 아니다. 만약 크로스플랫폼이 대상이라면 [argparse](https://github.com/cofyc/argparse)를 추천한다.

_

코드를 보고 바로 이해할 수 있도록, 간단 예제를 작성했다.


```

#include <stdio.h>

#include <stdlib.h>

#include <stdint.h>

#include <unistd.h>

#include <ctype.h>

#include <getopt.h>


/**

 * @file `getopt` by example

 */


int main(int argc, char** argv) {

int loglevel = 0;


/* Short Option Rules -----------------------------------------------------

*  - When there is a 'h' option, then

*    - `h`   means "option 'h' does not require value"

*    - `h:`  means "option 'h' require value"

*    - `h::` means "option 'h' require value optionally"

*  - Options can be concatenated; an user input

*    "-qwer" does same thing "-q -w -e -r" do

*/

const char* short_form = "n:l::vh";


/* Long Option Rules ------------------------------------------------------

*  - Should be structured with (name, has-arg, flag, val)

*    - `name` is entered in the form --name

*    - `flag` is accessed like this: `long_form[long_index].flag`

*    - `val` is a integer value that getopt_long() will return

*      when parsing succeeds.

*      - It can be any arbitary positive integer value

*      - However, it is recommended to use identical value

*        that used for short_form

*  - Must end with zero-filled strucuture

*  - If `has-arg` configured with `optional_argument`, user must provide

*    an argument like this "--something=1234" not "--something 1234"

*/

struct option long_form[] = {

{"name", required_argument, 0, 'n'},

{"log", optional_argument, &loglevel, 'l'},

{"version", no_argument, 0, 'v'},

{"help", no_argument, 0, 'h'},

{0,0,0,0}

};


/* Library Rules ----------------------------------------------------------

*  - Commandline arguments are automatically reordered by library

*  - When there is no more arugment to process, return value is -1

*  - Non-option arguments can be accessed in range `argv[optind:argc]`

*  - Invalid options are returned as a '?' character

*  - We can access option value as `optarg`

*  - If you don't need short option, give "" as optstring

*  - `longindex` should be used carefully. becuase,

*    - if current option is long type, it indicates index of option

*    - if current option is short type, it always set to 0

*/

while (1) {

int longindex = 0;

int choice = getopt_long(argc, argv, short_form, long_form, &longindex);

if (choice == -1) break;


switch( choice ) {

case '?':

// At this point, getopt_long will have already printed an error

break;


default:

printf("choice[%c]: index[%d] optarg[%s]\n",

choice, longindex, optarg);

}

}


/* Deal with non-option arguments here */

while ( optind < argc ) {

printf("arg[%d]=='%s'\n", optind, argv[optind]);

optind += 1;

}

return 0;

}


```

'C/C++' 카테고리의 다른 글

모든 네트워크 인터페이스의 MAC 주소 추출  (0) 2018.01.12
최적화  (0) 2017.08.06
flex bison 참고자료  (0) 2017.04.26
C라이브러리를 C++과 호환되도록 하는 방법  (0) 2017.04.06
Nonblocking I/O in C  (0) 2017.04.03