본문 바로가기

프로그래밍/그외

getopt_long 함수 사용예제

#include

#include // getopt_long() #include // strtol() #include // memset() /* struct option { const char *name; // 옵션의 긴 이름 int has_arg; // 옵션에 해당하는 자료 = 이후, 1: 필요, 0:불필요 int *flag; // 아래 지정한 갓ㅂ을 받을 수 있는 변수 주소 int val; // 이 값을 옵션에 따라 flag 변수에 대입. }; */ static struct option long_option[] = { // char *name, int has_arg, int *flag, int val { "file1", 1, 0, 0 }, { "num1", 1, 0, 0 }, { "file2", 1, 0, 0 }, { "num2", 1, 0, 0 }, { 0, 0, 0, 0 } }; int main(int argc, char *argv[]) { int c; int index; char file1[64]; int num1; int num2; char file2[64]; memset(file1, 0x0, sizeof(file1)); memset(file2, 0x0, sizeof(file2)); while ((c = getopt_long(argc, argv, "a:b:c:d:", long_option, &index)) != -1) { switch (c) { case 0 : if (strcmp(long_option[index].name, "file1") == 0) { strcpy(file1, optarg); printf( "file1: %s\n", file1); } else if (strcmp(long_option[index].name, "num1") == 0) { num1 = strtol(optarg, NULL, 16);    // 16진수 문자열을int로 printf("num1: 0x%x (%d)\n", num1, num1); } else if (strcmp(long_option[index].name, "num2") == 0) { num2 = strtol(optarg, NULL, 16); printf("num2: 0x%x (%d)\n", num2, num2); } else if (strcmp(long_option[index].name, "file2") == 0) { strcpy(file2, optarg); printf("file2: %s\n", file2); } break; case 'a' : strcpy(file1, optarg); printf( "file1: %s\n", file1); break; case 'b' : num1 = strtol(optarg, NULL, 16); printf("num1: 0x%x (%d)\n", num1, num1); break; case 'c' : strcpy(file2, optarg); printf("file2: %s\n", file2); break; case 'd' : num2 = strtol(optarg, NULL, 16); printf("num2: 0x%x (%d)\n", num2, num2); break; default : break; } } return 0; }


실행결과

$ ./getopt_long --file1=source.doc --num1=0x2600 --file2=list.txt -b --num2=0x4200
file1: source.doc
num1: 0x2600 (9728)
file2: list.txt
num1: 0x0 (0)

 $ ./getopt_long -a source.doc -c list.txt -b 0x2600 -d 0x4200
file1: source.doc
file2: list.txt
num1: 0x2600 (9728)
num2: 0x4200 (16896)



'프로그래밍 > 그외' 카테고리의 다른 글

[PyQt5] 다이얼로그의 사용  (0) 2019.07.02
[PyQt] QMainWindow  (0) 2019.06.24
엔디안 (바이트 오더링)과 구조체  (0) 2017.06.21
[SQL] sql 구문 몇가지  (0) 2014.06.13
[SQL] select 한 내용을 insert 하기  (0) 2014.06.12


Calendar
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Visits
Today
Yesterday