处理C / C ++中的命令行标志

时间:2021-04-28 20:45:54

I am looking for a very simple explanation/tutorial on what flags are. I understand that flags work indicate a command what to do. For example:

我正在寻找关于标志是什么的非常简单的解释/教程。我知道标志工作表明命令该做什么。例如:

rm -Rf test

I know that the rm command will remove the test folder and that the -Rf flags will force the command to erase not just the folder but the files in it.

我知道rm命令将删除测试文件夹,并且-Rf标志将强制命令不仅删除文件夹而且删除其中的文件。

But, where are the flags read/compiled??? What handles the flags? Can I, for example, write my own C/C++ program and designate different flags so that the program does different things? I hope I am asking the right questions. If not, please let me know.

但是,标志读取/编译在哪里?处理旗帜的是什么?例如,我可以编写自己的C / C ++程序并指定不同的标志,以便程序执行不同的操作吗?我希望我提出正确的问题。如果没有,请告诉我。

7 个解决方案

#1


6  

This simple program should demonstrate the arguments passed to the program (including the program name itself.)

这个简单的程序应该演示传递给程序的参数(包括程序名本身)。

Parsing, interpreting and using those arguments is up to the programmer (you), although there are libraries available to help.

解析,解释和使用这些参数取决于程序员(您),尽管有可用的库可以提供帮助。

int main(int argc, char* argv[])
{
    int i;
    for(i=0; i<argc; ++i)
    {   printf("Argument %d : %s\n", i, argv[i]);
    }
    return 0;
}

If you compile this program into a.out, and run it as:

如果将此程序编译为a.out,并将其运行为:

prompt$>  ./a.out ParamOne ParamTwo -rf x.c

You should see output:

你应该看到输出:

Argument 0 : a.out
Argument 1 : ParamOne
Argument 2 : ParamTwo
Argument 3 : -rf
Argument 4 : x.c

#2


11  

At the C level, command line arguments to a program appear in the parameters to the main function. For instance, if you compile this program:

在C级别,程序的命令行参数出现在main函数的参数中。例如,如果您编译此程序:

#include <stdio.h>
int main(int argc, char **argv)
{
    int i;
    for (i = 0; i < argc; i++)
        printf("argv[%d] = %s\n", i, argv[i]);
    return 0;
 }

and invoke it with the same arguments as your example 'rm' command, you get this:

并使用与示例'rm'命令相同的参数调用它,您得到:

$ ./a.out -Rf test
argv[0] = ./a.out
argv[1] = -Rf
argv[2] = test

As you can see, the first entry in argv is the name of the program itself, and the rest of the array entries are the command line arguments.

如您所见,argv中的第一个条目是程序本身的名称,其余的数组条目是命令行参数。

The operating system does not care at all what the arguments are; it is up to your program to interpret them. However, there are conventions for how they work, of which the following are the most important:

操作系统完全不关心参数是什么;由您的程序来解释它们。但是,有关于它们如何工作的惯例,其中以下是最重要的:

  • Arguments are divided into options and non-options. Options start with a dash, non-options don't.
  • 参数分为选项和非选项。选项以短划线开头,非选项不开始。

  • Options, as the name implies, are supposed to be optional. If your program requires some command-line arguments to do anything at all useful, those arguments should be non-options (i.e. they should not start with a dash).
  • 顾名思义,选项应该是可选的。如果你的程序需要一些命令行参数来做任何有用的事情,那些参数应该是非选项(即它们不应该以破折号开头)。

  • Options can be further divided into short options, which are a single dash followed by a single letter (-r, -f), and long options, which are two dashes followed by one or more dash-separated words (--recursive, --frobnicate-the-gourds). Short options can be glommed together into one argument (-rf) as long as none of them takes arguments (see below).
  • 选项可以进一步划分为短选项,即单个短划线后跟单个字母(-r,-f)和长选项,两个破折号后跟一个或多个破折号分隔的单词( - 递归, - -frobnicate最葫芦)。只要没有一个参数(参见下文),短选项可以一起组成一个参数(-rf)。

  • Options may themselves take arguments.
    • The argument to a short option -x is either the remainder of the argv entry, or if there is no further text in that entry, the very next argv entry whether or not it starts with a dash.
    • 短选项-x的参数是argv条目的其余部分,或者如果该条目中没有其他文本,则是下一个argv条目,无论它是否以短划线开头。

    • The argument to a long option is set off with an equals sign: --output=outputfile.txt.
    • long选项的参数用等号表示: - output = outputfile.txt。

  • 选项本身可以参数。短选项-x的参数是argv条目的其余部分,或者如果该条目中没有其他文本,则是下一个argv条目,无论它是否以短划线开头。 long选项的参数用等号表示: - output = outputfile.txt。

  • If at all possible, the relative ordering of distinct options (with their arguments) should have no observable effect.
  • 如果可能的话,不同选项(带有参数)的相对排序应该没有可观察到的影响。

  • The special option -- means "do not treat anything after this point on the command line as an option, even if it looks like one." This is so, for instance, you can remove a file named '-f' by typing rm -- -f.
  • 特殊选项 - 意味着“不要在命令行上的这一点之后处理任何内容作为选项,即使它看起来像一个。”例如,您可以通过键入rm - -f来删除名为“-f”的文件。

  • The special option - means "read standard input".
  • 特殊选项 - 表示“读取标准输入”。

  • There are a number of short option letters reserved by convention: the most important are
    • -v = be verbose
    • -v =详细

    • -q = be quiet
    • -q =安静

    • -h = print some help text
    • -h =打印一些帮助文本

    • -o file = output to file
    • -o file =输出到文件

    • -f = force (don't prompt for confirmation of dangerous actions, just do them)
    • -f =强制(不要提示确认危险行为,只需这样做)

  • 按惯例保留了许多短选项字母:最重要的是-v = be verbose -q = be quiet -h = print some help text -o file = output to file -f = force(不提示输入确认危险行为,就这样做吧)

There are a bunch of libraries for helping you parse command line arguments. The most portable, but also the most limited, of these is getopt, which is built into the C library on most systems nowadays. I recommend you read all of the documentation for GNU argp even if you don't want to use that particular one, because it'll further educate you in the conventions.

有许多库可以帮助您解析命令行参数。最便携,但也是最有限的是getopt,它现在在大多数系统的C库中内置。我建议您阅读GNU argp的所有文档,即使您不想使用该特定文档,因为它将进一步教育您遵守约定。

It's also worth mentioning that wildcard expansion (rm -rf *) is done before your program is ever invoked. If you ran the above sample program as ./a.out * in a directory containing only the binary and its source code you would get

还值得一提的是,通配符扩展(rm -rf *)是在调用程序之前完成的。如果您将上述示例程序作为./a.out *运行在仅包含二进制文件及其源代码的目录中

argv[0] = ./a.out
argv[1] = a.out
argv[2] = test.c

#3


4  

Actually you can write your own C++ programm which accepts commandline parameters like this:

实际上你可以编写自己的C ++程序,它接受这样的命令行参数:

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

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

The variable argc will contain the number of parameters, while the char* will contain the parameters itself.

变量argc将包含参数的数量,而char *将包含参数本身。

You can dispatch the parameters like this:

您可以像这样调度参数:

for (int i = 1; i < argc; i++)
{  
    if (i + 1 != argc)
    {
        if (strcmp(argv[i], "-filename") == 0) // This is your parameter name
        {                 
            char* filename = argv[i + 1];    // The next value in the array is your value
            i++;    // Move to the next flag
        }
    }
}

#4


2  

In your own C program you can process command line options in any way you see fit. Command line parameters in C come in the parameters of the main(int argc, char *argv[]) method as strings.

在您自己的C程序中,您可以以您认为合适的任何方式处理命令行选项。 C中的命令行参数作为字符串在main(int argc,char * argv [])方法的参数中。

And if you'd like to process command line parameters in a way similar to most UNIX commands, the function you're probably looking for is getopt()

如果您想以类似于大多数UNIX命令的方式处理命令行参数,那么您可能正在寻找的函数是getopt()

Good luck!

#5


0  

The easiest thing is to write your main() like so:

最简单的方法是编写main(),如下所示:

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

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

Then inside that main you decide what happens to the command line arguments or "flags". You find them in argv and their number is argc.

然后在那个main中你决定命令行参数或“flags”会发生什么。你在argv中找到它们,它们的编号是argc。

#6


0  

flags are arguments passed into the main entry point of the program. For example, in a C++ program you can have

flags是传递到程序主入口点的参数。例如,在C ++程序中,您可以拥有

int main(int arc, char* argv[]){
return 0;
}

your arc is the # of arguments passed in, and the pointer gives u the list of actual arguments. so for

你的arc是传入的参数的数量,指针给你实际的参数列表。因此对于

rm -Rf test

argc would be 3, and the argv array would contain your arguments. Notice argc >= 1 because the program name itself counts (rm). -RF is your 2nd parameter and test is your third.

argc将为3,argv数组将包含您的参数。注意argc> = 1,因为程序名本身计数(rm)。 -RF是你的第二个参数,测试是你的第三个参数。

So whenever you are typing commands in unix, you essentially are executing programs and passing them parameters that they operate on.

因此,无论何时在unix中键入命令,您基本上都在执行程序并传递它们所操作的参数。

If you are really REALLY interested in the unix OS, you should look up forks and how they work. This can get pretty confusing to a newcomer though, so only if you are really interested in OS and how programs are executed.

如果你真的真的对unix操作系统感兴趣,你应该查找分叉以及它们是如何工作的。这对于新手来说可能会让人感到困惑,所以只有当你真的对操作系统以及如何执行程序感兴趣时才会这样。

#7


0  

GNU libc, which is very likely available on your system, has a library for this called getopt that can be used to parse the options in a sensible fashion. There are examples to get you started in the documentation linked below.

GNU libc很可能在您的系统上可用,它有一个名为getopt的库,可用于以合理的方式解析选项。有一些示例可以帮助您开始下面链接的文档。

http://www.gnu.org/software/libc/manual/html_node/Getopt.html#Getopt

#1


6  

This simple program should demonstrate the arguments passed to the program (including the program name itself.)

这个简单的程序应该演示传递给程序的参数(包括程序名本身)。

Parsing, interpreting and using those arguments is up to the programmer (you), although there are libraries available to help.

解析,解释和使用这些参数取决于程序员(您),尽管有可用的库可以提供帮助。

int main(int argc, char* argv[])
{
    int i;
    for(i=0; i<argc; ++i)
    {   printf("Argument %d : %s\n", i, argv[i]);
    }
    return 0;
}

If you compile this program into a.out, and run it as:

如果将此程序编译为a.out,并将其运行为:

prompt$>  ./a.out ParamOne ParamTwo -rf x.c

You should see output:

你应该看到输出:

Argument 0 : a.out
Argument 1 : ParamOne
Argument 2 : ParamTwo
Argument 3 : -rf
Argument 4 : x.c

#2


11  

At the C level, command line arguments to a program appear in the parameters to the main function. For instance, if you compile this program:

在C级别,程序的命令行参数出现在main函数的参数中。例如,如果您编译此程序:

#include <stdio.h>
int main(int argc, char **argv)
{
    int i;
    for (i = 0; i < argc; i++)
        printf("argv[%d] = %s\n", i, argv[i]);
    return 0;
 }

and invoke it with the same arguments as your example 'rm' command, you get this:

并使用与示例'rm'命令相同的参数调用它,您得到:

$ ./a.out -Rf test
argv[0] = ./a.out
argv[1] = -Rf
argv[2] = test

As you can see, the first entry in argv is the name of the program itself, and the rest of the array entries are the command line arguments.

如您所见,argv中的第一个条目是程序本身的名称,其余的数组条目是命令行参数。

The operating system does not care at all what the arguments are; it is up to your program to interpret them. However, there are conventions for how they work, of which the following are the most important:

操作系统完全不关心参数是什么;由您的程序来解释它们。但是,有关于它们如何工作的惯例,其中以下是最重要的:

  • Arguments are divided into options and non-options. Options start with a dash, non-options don't.
  • 参数分为选项和非选项。选项以短划线开头,非选项不开始。

  • Options, as the name implies, are supposed to be optional. If your program requires some command-line arguments to do anything at all useful, those arguments should be non-options (i.e. they should not start with a dash).
  • 顾名思义,选项应该是可选的。如果你的程序需要一些命令行参数来做任何有用的事情,那些参数应该是非选项(即它们不应该以破折号开头)。

  • Options can be further divided into short options, which are a single dash followed by a single letter (-r, -f), and long options, which are two dashes followed by one or more dash-separated words (--recursive, --frobnicate-the-gourds). Short options can be glommed together into one argument (-rf) as long as none of them takes arguments (see below).
  • 选项可以进一步划分为短选项,即单个短划线后跟单个字母(-r,-f)和长选项,两个破折号后跟一个或多个破折号分隔的单词( - 递归, - -frobnicate最葫芦)。只要没有一个参数(参见下文),短选项可以一起组成一个参数(-rf)。

  • Options may themselves take arguments.
    • The argument to a short option -x is either the remainder of the argv entry, or if there is no further text in that entry, the very next argv entry whether or not it starts with a dash.
    • 短选项-x的参数是argv条目的其余部分,或者如果该条目中没有其他文本,则是下一个argv条目,无论它是否以短划线开头。

    • The argument to a long option is set off with an equals sign: --output=outputfile.txt.
    • long选项的参数用等号表示: - output = outputfile.txt。

  • 选项本身可以参数。短选项-x的参数是argv条目的其余部分,或者如果该条目中没有其他文本,则是下一个argv条目,无论它是否以短划线开头。 long选项的参数用等号表示: - output = outputfile.txt。

  • If at all possible, the relative ordering of distinct options (with their arguments) should have no observable effect.
  • 如果可能的话,不同选项(带有参数)的相对排序应该没有可观察到的影响。

  • The special option -- means "do not treat anything after this point on the command line as an option, even if it looks like one." This is so, for instance, you can remove a file named '-f' by typing rm -- -f.
  • 特殊选项 - 意味着“不要在命令行上的这一点之后处理任何内容作为选项,即使它看起来像一个。”例如,您可以通过键入rm - -f来删除名为“-f”的文件。

  • The special option - means "read standard input".
  • 特殊选项 - 表示“读取标准输入”。

  • There are a number of short option letters reserved by convention: the most important are
    • -v = be verbose
    • -v =详细

    • -q = be quiet
    • -q =安静

    • -h = print some help text
    • -h =打印一些帮助文本

    • -o file = output to file
    • -o file =输出到文件

    • -f = force (don't prompt for confirmation of dangerous actions, just do them)
    • -f =强制(不要提示确认危险行为,只需这样做)

  • 按惯例保留了许多短选项字母:最重要的是-v = be verbose -q = be quiet -h = print some help text -o file = output to file -f = force(不提示输入确认危险行为,就这样做吧)

There are a bunch of libraries for helping you parse command line arguments. The most portable, but also the most limited, of these is getopt, which is built into the C library on most systems nowadays. I recommend you read all of the documentation for GNU argp even if you don't want to use that particular one, because it'll further educate you in the conventions.

有许多库可以帮助您解析命令行参数。最便携,但也是最有限的是getopt,它现在在大多数系统的C库中内置。我建议您阅读GNU argp的所有文档,即使您不想使用该特定文档,因为它将进一步教育您遵守约定。

It's also worth mentioning that wildcard expansion (rm -rf *) is done before your program is ever invoked. If you ran the above sample program as ./a.out * in a directory containing only the binary and its source code you would get

还值得一提的是,通配符扩展(rm -rf *)是在调用程序之前完成的。如果您将上述示例程序作为./a.out *运行在仅包含二进制文件及其源代码的目录中

argv[0] = ./a.out
argv[1] = a.out
argv[2] = test.c

#3


4  

Actually you can write your own C++ programm which accepts commandline parameters like this:

实际上你可以编写自己的C ++程序,它接受这样的命令行参数:

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

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

The variable argc will contain the number of parameters, while the char* will contain the parameters itself.

变量argc将包含参数的数量,而char *将包含参数本身。

You can dispatch the parameters like this:

您可以像这样调度参数:

for (int i = 1; i < argc; i++)
{  
    if (i + 1 != argc)
    {
        if (strcmp(argv[i], "-filename") == 0) // This is your parameter name
        {                 
            char* filename = argv[i + 1];    // The next value in the array is your value
            i++;    // Move to the next flag
        }
    }
}

#4


2  

In your own C program you can process command line options in any way you see fit. Command line parameters in C come in the parameters of the main(int argc, char *argv[]) method as strings.

在您自己的C程序中,您可以以您认为合适的任何方式处理命令行选项。 C中的命令行参数作为字符串在main(int argc,char * argv [])方法的参数中。

And if you'd like to process command line parameters in a way similar to most UNIX commands, the function you're probably looking for is getopt()

如果您想以类似于大多数UNIX命令的方式处理命令行参数,那么您可能正在寻找的函数是getopt()

Good luck!

#5


0  

The easiest thing is to write your main() like so:

最简单的方法是编写main(),如下所示:

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

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

Then inside that main you decide what happens to the command line arguments or "flags". You find them in argv and their number is argc.

然后在那个main中你决定命令行参数或“flags”会发生什么。你在argv中找到它们,它们的编号是argc。

#6


0  

flags are arguments passed into the main entry point of the program. For example, in a C++ program you can have

flags是传递到程序主入口点的参数。例如,在C ++程序中,您可以拥有

int main(int arc, char* argv[]){
return 0;
}

your arc is the # of arguments passed in, and the pointer gives u the list of actual arguments. so for

你的arc是传入的参数的数量,指针给你实际的参数列表。因此对于

rm -Rf test

argc would be 3, and the argv array would contain your arguments. Notice argc >= 1 because the program name itself counts (rm). -RF is your 2nd parameter and test is your third.

argc将为3,argv数组将包含您的参数。注意argc> = 1,因为程序名本身计数(rm)。 -RF是你的第二个参数,测试是你的第三个参数。

So whenever you are typing commands in unix, you essentially are executing programs and passing them parameters that they operate on.

因此,无论何时在unix中键入命令,您基本上都在执行程序并传递它们所操作的参数。

If you are really REALLY interested in the unix OS, you should look up forks and how they work. This can get pretty confusing to a newcomer though, so only if you are really interested in OS and how programs are executed.

如果你真的真的对unix操作系统感兴趣,你应该查找分叉以及它们是如何工作的。这对于新手来说可能会让人感到困惑,所以只有当你真的对操作系统以及如何执行程序感兴趣时才会这样。

#7


0  

GNU libc, which is very likely available on your system, has a library for this called getopt that can be used to parse the options in a sensible fashion. There are examples to get you started in the documentation linked below.

GNU libc很可能在您的系统上可用,它有一个名为getopt的库,可用于以合理的方式解析选项。有一些示例可以帮助您开始下面链接的文档。

http://www.gnu.org/software/libc/manual/html_node/Getopt.html#Getopt