C语言 在 C/C++ 中处理命令行标志
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14737957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handling command line flags in C/C++
提问by Fabio Gomez
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++ 程序并指定不同的标志以便程序执行不同的操作吗?我希望我问的是正确的问题。如果没有,请告诉我。
采纳答案by abelenky
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
回答by zwol
At the C level, command line arguments to a program appear in the parameters to the mainfunction. 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 argvis 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 optionsand 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 notstart with a dash).
- Options can be further divided into shortoptions, which are a single dash followed by a single letter (
-r,-f), and longoptions, 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). - Options may themselves take arguments.
- The argument to a shortoption
-xis either the remainder of theargventry, or if there is no further text in that entry, the very nextargventry whether or notit starts with a dash. - The argument to a longoption is set off with an equals sign:
--output=outputfile.txt.
- The argument to a shortoption
- 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 typingrm -- -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-q= be quiet-h= print some help text-ofile= output to file-f= force (don't prompt for confirmation of dangerous actions, just do them)
- 参数分为options和non-options。选项以破折号开头,非选项则不。
- 顾名思义,选项应该是可选的。如果你的程序需要一些命令行参数,在所有有用的做任何事情,这些参数应该是非选项(即它们应该不以破折号开始)。
- 选项可进一步分为短选项,即单个破折号后跟单个字母 (
-r,-f) 和长选项,即两个破折号后跟一个或多个破折号分隔的单词 (--recursive,--frobnicate-the-gourds)。短选项可以合并为一个参数 (-rf),只要它们都不带参数(见下文)。 - 选项本身可能带有参数。
- 短选项的参数
-x是argv条目的其余部分,或者如果该条目中没有其他文本,则是下一个argv条目,无论它是否以破折号开头。 - 长选项的参数用等号分隔:
--output=outputfile.txt。
- 短选项的参数
- 如果可能的话,不同选项(及其参数)的相对顺序应该没有可观察到的影响。
- 特殊选项的
--意思是“不要将命令行上这一点之后的任何内容视为选项,即使它看起来像一个选项。” 例如,您可以-f通过键入删除名为“ ”的文件rm -- -f。 - 特殊选项的
-意思是“读取标准输入”。 - 按照惯例保留了许多简短的选项字母:最重要的是
-v= 冗长-q=安静-h= 打印一些帮助文本-o文件= 输出到文件-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 argpeven 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 beforeyour 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
回答by Xenogenesis
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
}
}
}
回答by Leo supports Monica Cellio
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!
祝你好运!
回答by Bernd Elkemann
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 youdecide what happens to the command line arguments or "flags". You find them in argv and their number is argc.
然后在该 main 中,您决定命令行参数或“标志”会发生什么。您可以在 argv 中找到它们,它们的编号是 argc。
回答by 75inchpianist
flags are arguments passed into the main entry point of the program. For example, in a C++ program you can have
标志是传递到程序主入口点的参数。例如,在 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
您的弧是传入的参数数量,指针为您提供实际参数列表。因此对于
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 是您的第二个参数,而 test 是您的第三个参数。
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 操作系统非常感兴趣,您应该查看分叉及其工作原理。但是,这可能会让新手感到非常困惑,因此只有当您真正对操作系统和程序的执行方式感兴趣时。
回答by Michael Conlen
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
http://www.gnu.org/software/libc/manual/html_node/Getopt.html#Getopt

