C语言解析命令行参数

原文地址:C语言解析命令行参数 -- 无敌牛

欢迎参观我的个人博客:无敌牛 -- 技术/著作/典籍/分享等

C语言有一个 getopt 函数,可以对命令行进行解析,下面给出一个示例,用的时候可以直接copy过去修改,很方便。

代码:

复制代码
//  main.c
//  gcc -Wall main.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void usage(char* exec_file) {
    printf("\n");
    printf("Usage:\n");
    printf("\n");
    printf("%s options:\n", exec_file);
    printf(" -C, -c  指定配置文件,否则使用默认配置文件[/xxx/xxxx]\n");
    printf(" -F, -f  强制执行\n");
    printf(" -H, -h  打印此页面\n");
    printf("\n");
}


typedef struct _myargs_t{
    char config_path[1024] ;
    int f_flag ;
} myargs_t ;

int main(int argc, char* argv[]) {
    myargs_t myargs = {
        "/xxx/xxxx",
        0
    } ;
    char opt ;
    while ((opt = getopt(argc, argv, "C:c:FfHh")) != -1) {
        switch (opt) {
            case 'C':
            case 'c':
                printf("get options [%c] arg[%s]\n", opt, optarg) ;
                snprintf(myargs.config_path, sizeof(myargs.config_path), "%s", optarg) ;
                break;
            case 'F':
            case 'f':
                printf("get options [%c]\n", opt) ;
                myargs.f_flag = 1 ;
                break;
            case 'h':
            case 'H':
                usage(argv[0]);
                return 0 ;
            default:
                usage(argv[0]);
                printf("没有此选项[%c], 请重新选择!\n", opt);
                return 0;
        }
    }
    printf("config_path[%s]  f_flag[%d]\n", myargs.config_path, myargs.f_flag ) ;
}

编译测试:

相关推荐
RuoZoe1 天前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
祈安_4 天前
C语言内存函数
c语言·后端
郑州光合科技余经理6 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1236 天前
matlab画图工具
开发语言·matlab
dustcell.6 天前
haproxy七层代理
java·开发语言·前端
norlan_jame6 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone6 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054966 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
czy87874756 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
遥遥江上月6 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js