[C/C++] 명령줄 인자 처리하기

yjseo·2024년 10월 8일

sipp 코드를 읽다가 명령줄 인자를 처리하는 방법에 대해 배웠다.
사실 잘 모르겠어서 챗지피티한테 알려달라고 했음

option 구조체 만들기

struct option
{
    const char *option;
    const char *help;
    int type;
    void *data;
    int pass;
};

option table 배열 만들기

struct option option_table[] = {
    {"-t", "총 실행 시간(초) 설정 ", 2, &totalsec, 1},
    {"-n", "갱신 간격(초) 설정", 1, &nsec, 1},
    {"--help", "도움말 메시지 출력", 0, nullptr, 0},
};

find_option() 구현하기

struct option *find_option(const char *opt)
{
    int max = sizeof(option_table) / sizeof(option_table[0]);

    if (opt[0] != '-')
        return nullptr;

    for (int i = 0; i < max; i++)
    {
        if (!strcmp(option_table[i].option, opt))
            return &(option_table[i]);
    }

    return nullptr;
}

main() 함수에서 인자 처리하기

#define HELP 0
#define INTERVAL 1
#define TOTAL_SEC 2

int main(int argc, char *argv[])
{
    // argument 처리
    for (int i = 1; i < argc; i++)
    {
        struct option *opt = find_option(argv[i]);
        if (opt)
        {
            switch (opt->type)
            {
            case HELP:
                break;
            case INTERVAL:
            case TOTAL_SEC:
                if (i + 1 < argc)
                {
                    if (opt->data != nullptr)
                        *(static_cast<int *>(opt->data)) = stoi(argv[++i]);
                }
                else
                {
                    cerr << "Option " << opt->option << " requires an argument" << endl;
                    return 1;
                }
                break;
            default:
                cerr << "Unknown option type" << endl;
                return 1;
            }

            if (opt->pass == 0) // help 옵션을 먼저 처리
            {
                for (const auto &opt : option_table)
                    cout << opt.option << ": " << opt.help << endl;
                return 0;
            }
        }
        else
        {
            cerr << "Unknown option: " << argv[i] << endl;
            return 1;
        }
    }
}

인자로 들어오는 문자열을 한글자씩 읽어서 struct option *find_option(const char* opt) 에 전달해서- (옵션)을 찾는다.
옵션이 맞으면 switch문을 이용해서 옵션에 맞게 처리를 한다.

실행

이런 식으로 실행하면 된다.

./main --help
-n: n초에 한 번씩 출력
--help: 도움말 메시지 출력

./main -n 5

근데 -t 옵션도 구현했던걸로 기억하는데 뭐지 아닌가
두 달전에 만든거라 기억이 안난다

참고
sipp 깃허브: https://github.com/SIPp/sipp
챗지피티

profile
저 뭐해먹고 살아요..🥺

0개의 댓글