c - 正确解析 C 中的命令行参数

标签 c command-line-arguments

我想做的是接受命令行参数并根据参数更改一些变量。我附上了一大块代码,因为整个代码大约有 400 行。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {

    char somestring[500];
    int ca=0;
    if (argc==1) //if no arguments are specified use defaults
    {
    }
    else
    {
        while(ca<argc)
        {
               ca++
            if(strcmp(argv[ca],"-f")==0)
            {
                printf("This works");
                ca++; 
                if(strcmp(argv[ca],"red")==0){
                    printf("this will print red\n");
                }
                else{
                    printf("invalid color");
                }
            }
            if(strcmp(argv[ca),"")==0)
            {
                printf("invalid argument");
            }
            else {
                strcat(somestring,argv[ca]);
            }
        }
        printf("%s",somestring);
    }
}

如果用户输入:

./foobar -f red this is a string

程序应该打印:

"this will print red this is a string"

如果用户输入:

./foobar -f red

程序应该打印“命令行参数的数量无效”。

最简单的方法是什么?我已经尝试了很多可能性但没有运气。 不同数量的参数是我的主要问题(我还有超过 5 个选项,例如..-f -b -h -w -e)

帮助将不胜感激。如果你愿意,我可以添加我的整个代码。

最佳答案

正确的方法是使用许多现有的解析器库之一,而不是自己手动解析。它更简单、更强大,并且省去了重新发明轮子的麻烦。

GNU libc 手册建议了一些库,具体取决于您想要的花哨/标准: http://www.gnu.org/software/libc/manual/html_node/Parsing-Program-Arguments.html

  • getopt:如另一个答案所述
  • argp:我通常的选择
  • 子选项:用于复杂的解决方案

关于c - 正确解析 C 中的命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8374810/

相关文章:

具有可重复参数对的 Python argparse 参数

Bash if 语句不能正常工作

arrays - 在右值的情况下,系统如何知道它所指向的地址类型?

java - 如何在 NetBeans VM 选项中指定显示 SplashScreen 的时间?

perl - 在 Perl 中处理不同基数的命令行参数

wix - 使用 WiX Burn 静默安装 SqlLocalDB.msi #EDIT3

python : Socket Sending Struct(having C stuct as Example)

c - 单 socket 多线程接收器

c - 我们如何访问堆栈变量而不弹出它们?

谁能告诉我这行代码是什么意思?