【问题标题】:I'd like a C program to accept arguments from linux command line我想要一个 C 程序来接受来自 linux 命令行的参数
【发布时间】:2019-12-08 02:57:51
【问题描述】:

我正在尝试将文本分析为输入,它将根据输入到命令提示符(例如./a.out -a -b 20 -c 3)的参数及其值以任意顺序进行修改和打印,它们是可选的,不必须输入。我如何在 C 代码中实现这些参数以及如何找出它们的值? (为了便于说明,您可以使用前面提到的 -a、-b 和 -c。)

谢谢。

【问题讨论】:

  • 研究getopt()库调用;这旨在从命令行获取argcargv 并允许您使用它们。
  • getopt or argp 是在 Linux 上使用的方式。

标签: c command-line-arguments


【解决方案1】:

通常你这样声明你的主函数,

int main( int argc, char *argv[] )  {}

然后,当你从命令行调用你的程序时,

./a.out 1 2 3

argc 将是一个包含 4(传递的参数数量)的 int

argv[1]argv[3] 中,您分别有指向参数1 到3 的指针。而在argv[0] 中,您有一个指向程序名称的指针。

【讨论】:

    【解决方案2】:

    (我不是在为这个投票。感谢@SteveFriedl。)

    由于我从未听说过getopt() 并且一直为这种事情编写自己的解析器而感到内疚,请参阅下面的示例。

    请注意,getopt 似乎只接受单字符参数名称。例如,您可以使用-f hello.text,但不能使用-filename hello.txtoptindoptarg 是在 unistd.h 中声明的(呃)全局变量。

    (请注意,通过argv[] 自己实现这一点并不难,这可能会产生更灵活的解决方案。)

    Shamelessly lifted from Geeks for Geeks

    // copied from https://www.geeksforgeeks.org/getopt-function-in-c-to-parse-command-line-arguments/
    // Program to illustrate the getopt() 
    // function in C 
    
    #include <stdio.h> 
    #include <unistd.h> 
    
    int main(int argc, char *argv[]) 
    { 
        int opt; 
    
        // put ':' in the starting of the 
        // string so that program can 
        //distinguish between '?' and ':' 
        while((opt = getopt(argc, argv, “:if:lrx”)) != -1) 
        { 
            switch(opt) 
            { 
                case ‘i’: 
                case ‘l’: 
                case ‘r’: 
                    printf(“option: %c\n”, opt); 
                    break; 
                case ‘f’: 
                    printf(“filename: %s\n”, optarg); 
                    break; 
                case ‘:’: 
                    printf(“option needs a value\n”); 
                    break; 
                case ‘?’: 
                    printf(“unknown option: %c\n”, optopt); 
                    break; 
            } 
        } 
    
        // optind is for the extra arguments 
        // which are not parsed 
        for(; optind < argc; optind++){  
            printf(“extra arguments: %s\n”, argv[optind]); 
        } 
    
        return 0; 
    } 
    

    那么,

    ./a.out -i -f file.txt -lr -x 'hero'
    

    生产

    option: i
    filename: file.txt
    option: l
    option: r
    unknown option: x
    extra arguments: hero
    

    【讨论】:

      猜你喜欢
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 2015-04-20
      • 2011-06-15
      • 1970-01-01
      • 2017-08-18
      • 2020-10-02
      • 1970-01-01
      相关资源
      最近更新 更多