반응형
리눅스상에서 우리는 쉽게
-o, -i, -p, -a, -l 등 옵션을 적용할 수 있는 프로그램을 볼 수 있다.
위와같은 프로그램은 getopt로 간단하게 구현할 수 있다.

필요 Include 파일
#include "stdio.h"
#include "stdlib.h"
#include <unistd.h>

사용하는 함수
int getopt(int argc, char ** argv, const char *options)   

사용되는 변수
int opterr : 이변수값에 0이아닌 숫자를 넣으면, 알지 못하는 옵션이 들어오면 표준 에러 메세지를 출력해 준다

int optopt :  알지 못하는 옵션의 문자를 이 변수에 저장한다.

int optind : 다음 옵션의 index값을 지정해 준다. 이를 활용하여 옵션이 있는경우 없는경우 구분 할 수 있다. 초기값은 1.

cahr * optarg : 인수를 받아들이는 옵션들의 argment를 저장해 준다.

소스코드

    int oc;
    ci_name = init;
    int num_sfr_in=0, num_sfr_out=0;
    int num_con=0;
    if(argc == 1){
        printf ( "./citemgen <optinons> \n        -n    :    Custon Instruction Name\n        -i    :    Number of input SFR\n        -o    :    Number of output SFR\n        -c    :    Number of Control bit\n\n");
        return 1;
    } else {
//Get opt를 통하여 현재 존재하는 모든 option을 받아온다.
// " " 안에 들어가는 내용은, 어떠한 옵션들을 적용할 수 있는지 나타내 준다
// 뒤에: 가 붙을 경우 -o test 와 같이 추가 인자를 필요로 한다는 뜻이다.
        while ((oc=getopt(argc,argv,":n:i:o:c:")) != -1 )
        {
            switch(oc)
            {
                case 'n':
                    //fprintf(stdout,"option : n\n");
                    ci_name=optarg;
                    break;
                case 'i':
                    //fprintf(stdout,"option : si\n");
                    num_sfr_in=atoi(optarg);
                    break;
                case 'o':
                  //  fprintf(stdout,"option : si\n");
                    num_sfr_out=atoi(optarg);
                     break;
                case 'c':
                    //fprintf(stdout,"option : si\n");
                    num_con=atoi(optarg);
                    break;
//추가 인자가 필요한 Function인데, 추가 인자가 오지 않았을 경우
                case ':':
                    fprintf(stderr,"%s : option '-%c' requires an argument\n",argv[0],optopt);
                    break;
//모르는 인자가 옵션으로 나타났을 경우
                case '?':
                default:
                    fprintf(stderr,"%s : option '-%c' is invalid : ignored\n",argv[0],optopt);
                    break;
            }
        }
옵션이 없는경우의 처리

   for(int i = optind; i < argc ; i++){
         ...
   }
반응형

+ Recent posts