Linux 从命令行将参数传递给 C 程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/498320/
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
Pass arguments into C program from command line
提问by BlackCow
So I'm in Linux and I want to have a program accept arguments when you execute it from the command line.
所以我在 Linux 中,我想让程序在从命令行执行时接受参数。
For example,
例如,
./myprogram 42 -b -s
./myprogram 42 -b -s
So then the program would store that number 42 as an int and execute certain parts of code depending on what arguments it gets like -b or -s.
因此,程序会将数字 42 存储为 int 并根据它获得的参数(如 -b 或 -s)执行某些代码部分。
采纳答案by CMS
You could use getopt.
您可以使用getopt。
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main (int argc, char **argv)
{
int bflag = 0;
int sflag = 0;
int index;
int c;
opterr = 0;
while ((c = getopt (argc, argv, "bs")) != -1)
switch (c)
{
case 'b':
bflag = 1;
break;
case 's':
sflag = 1;
break;
case '?':
if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\x%x'.\n",
optopt);
return 1;
default:
abort ();
}
printf ("bflag = %d, sflag = %d\n", bflag, sflag);
for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}
回答by Greg Hewgill
In C, this is done using arguments passed to your main()
function:
在 C 中,这是使用传递给main()
函数的参数完成的:
int main(int argc, char *argv[])
{
int i = 0;
for (i = 0; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
return 0;
}
More information can be found online such as this Arguments to mainarticle.
回答by womble
Take a look at the getopt library; it's pretty much the gold standard for this sort of thing.
看看 getopt 库;这几乎是这类事情的黄金标准。
回答by jfs
Consider using getopt_long()
. It allows both short and long options in any combination.
考虑使用getopt_long()
. 它允许任意组合的短期和长期期权。
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
/* Flag set by `--verbose'. */
static int verbose_flag;
int
main (int argc, char *argv[])
{
while (1)
{
static struct option long_options[] =
{
/* This option set a flag. */
{"verbose", no_argument, &verbose_flag, 1},
/* These options don't set a flag.
We distinguish them by their indices. */
{"blip", no_argument, 0, 'b'},
{"slip", no_argument, 0, 's'},
{0, 0, 0, 0}
};
/* getopt_long stores the option index here. */
int option_index = 0;
int c = getopt_long (argc, argv, "bs",
long_options, &option_index);
/* Detect the end of the options. */
if (c == -1)
break;
switch (c)
{
case 0:
/* If this option set a flag, do nothing else now. */
if (long_options[option_index].flag != 0)
break;
printf ("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s", optarg);
printf ("\n");
break;
case 'b':
puts ("option -b\n");
break;
case 's':
puts ("option -s\n");
break;
case '?':
/* getopt_long already printed an error message. */
break;
default:
abort ();
}
}
if (verbose_flag)
puts ("verbose flag is set");
/* Print any remaining command line arguments (not options). */
if (optind < argc)
{
printf ("non-option ARGV-elements: ");
while (optind < argc)
printf ("%s ", argv[optind++]);
putchar ('\n');
}
return 0;
}
Related:
有关的:
回答by sastanin
Instead of getopt()
, you may also consider using argp_parse()
(an alternative interface to the same library).
除了getopt()
,您还可以考虑使用argp_parse()
(同一库的替代接口)。
From libc manual:
从libc 手册:
getopt
is more standard (the short-option only version of it is a part of the POSIX standard), but usingargp_parse
is often easier, both for very simple and very complex option structures, because it does more of the dirty work for you.
getopt
更标准(它的仅短选项版本是 POSIX 标准的一部分),但是argp_parse
对于非常简单和非常复杂的选项结构,使用 通常更容易,因为它为您做了更多的脏活。
But I was always happy with the standard getopt
.
但我总是对标准感到满意getopt
。
N.B. GNU getopt
with getopt_long
is GNU LGPL.
NB GNUgetopt
与getopt_long
是GNU LGPL。
回答by dmckee --- ex-moderator kitten
Other have hit this one on the head:
其他人打了这个头:
- the standard arguments to
main(int argc, char **argv)
give you direct access to the command line (after it has been mangled and tokenized by the shell) - there are very standard facility to parse the command line:
getopt()
andgetopt_long()
main(int argc, char **argv)
使您可以直接访问命令行的标准参数(在它被 shell 修改和标记后)- 有非常标准的设施,以解析命令行:
getopt()
和getopt_long()
but as you've seen the code to use them is a bit wordy, and quite idomatic. I generally push it out of view with something like:
但是正如您所看到的,使用它们的代码有点冗长,而且非常惯用。我通常会使用以下内容将其从视图中移除:
typedef
struct options_struct {
int some_flag;
int other_flage;
char *use_file;
} opt_t;
/* Parses the command line and fills the options structure,
* returns non-zero on error */
int parse_options(opt_t *opts, int argc, char **argv);
Then first thing in main:
然后主要的第一件事:
int main(int argc, char **argv){
opt_t opts;
if (parse_options(&opts,argc,argv)){
...
}
...
}
Or you could use one of the solutions suggested in Argument-parsing helpers for C/UNIX.
或者您可以使用Argument-parsing helpers for C/UNIX 中建议的解决方案之一。