使用 getopt 获取命令行参数

test.c
/*
 * Build:
 *   gcc -g -o test test.c
 *
 * Usage:
 *   ./test [-c max number of child] 'keyword' 'log file'
 *
 */

#include <stdio.h>
#include <string.h>
#include <getopt.h>

int main(int argc, char **argv)
{
    int i;
    int ch;
    const char *args = "c:h";
    while ((ch = getopt(argc, argv, args)) != -1) {
        switch (ch) {
            case 'c':
                max_num_child = atoi(optarg);
                break;
            case 'h':
            default:
                usage(argv[0]);
                exit(0);
        }
    }
    if ( (argc - optind) != 2) {
        usage(argv[0]);
        exit(0);
    }

    snprintf(keyword, sizeof(keyword), "%s", argv[optind++]);
    snprintf(log_file, sizeof(log_file), "%s", argv[optind++]);

    printf("#####################################\n");
    printf("#### max number of child: %d\n", max_num_child);
    printf("#### keyword: %s\n", keyword);
    printf("#### log file: %s\n", log_file);
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容