[英]Pass arguments into C program from command line
所以我在Linux中,當你從命令行執行它時,我希望有一個程序接受參數。
例如,
./myprogram 42 -b -s
那么程序會將該數字42存儲為int並執行某些代碼部分,具體取決於它是什么參數-b或-s。
你可以使用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;
}
考慮使用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;
}
有關:
看看getopt庫; 這幾乎是這類事情的黃金標准。
您也可以考慮使用argp_parse()
(同一個庫的替代接口getopt()
,而不是getopt()
)。
來自libc手冊 :
getopt
更標准(它的短選項只是POSIX標准的一部分),但是對於非常簡單和非常復雜的選項結構,使用argp_parse
通常更容易,因為它為你做了更多的臟工作。
但我總是對標准的getopt
感到滿意。
使用getopt_long
NB GNU getopt
是GNU LGPL。
其他人在頭上擊中了這個:
main(int argc, char **argv)
的標准參數使您可以直接訪問命令行(在shell被修改並標記化之后) getopt()
和getopt_long()
但正如你所看到的那樣,使用它們的代碼有點冗長,而且非常獨特。 我通常將它推出視圖,例如:
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);
然后主要的第一件事:
int main(int argc, char **argv){
opt_t opts;
if (parse_options(&opts,argc,argv)){
...
}
...
}
或者您可以使用C / UNIX的Argument-parsing helpers中建議的解決方案之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.