红联Linux门户
Linux帮助

Linux main命令行参数解析最好用的例子

发布时间:2014-11-24 15:27:12来源:linux网站作者:yangzhifu

或许是我见得少,反正这是目前遇到最好命令行参数例子,下面给出源码及简单介绍:

第一部分:主要是声明一个结构体,将解析到的参数放在结构体中,同时还给出一个默认参数;

 16 #include <getopt.h>

 61 typedef struct Args {
 62     VideoStd_Type  videoStd;
 63     Char          *videoStdString;
 64     Sound_Input    soundInput;
 65     Capture_Input  videoInput;
 66     Char          *speechFile;
 67     Char          *videoFile;
 68     Codec         *speechEncoder;
 69     Codec         *videoEncoder;
 70     Int32          imageWidth;
 71     Int32          imageHeight;
 72     Int            videoBitRate;
 73     Int            keyboard;
 74     Int            time;
 75     Int            osd;
 76     Int            interface;
 77 } Args;
 78
 79 #define DEFAULT_ARGS \
 80     { VideoStd_D1_NTSC, "D1 NTSC", Sound_Input_MIC, Capture_Input_COMPOSITE, \
 81       NULL, NULL, NULL, NULL, 0, 0, -1, FALSE, FOREVER, FALSE, FALSE }


第二部分:核心部分,标准的信息打印,和命令行参数解析函数

118 /**********************************
119  * usage
120  **********************************/
121 static void usage(void)
122 {
123     fprintf(stderr, "Usage: encode [options]\n\n"
124       "Options:\n"
125       "-s | --speechfile       Speech file to record to\n"
126       "-v | --videofile        Video file to record to\n"
127       "-y | --display_standard Video standard to use for display (see below).\n"
128       "-r | --resolution       Video resolution ('width'x'height')\n"
129       "                        [video standard default]\n"
130       "-b | --videobitrate     Bit rate to encode video at [variable]\n"
131       "-x | --svideo           Use s-video instead of composite video \n"
132       "                        input [off]\n"
133       "-l | --linein           Use linein for encoding sound instead of mic \n"
134       "                        [off]\n"
135       "-k | --keyboard         Enable keyboard interface [off]\n"
136       "-t | --time             Number of seconds to run the demo [infinite]\n"
137       "-o | --osd              Show demo data on an OSD [off]\n"
138       "-i | --interface        Launch the demo interface when exiting [off]\n"
139       "-h | --help             Print this message\n\n"
140       "Video standards available:\n"
141       "\t1\tD1 @ 30 fps (NTSC) [Default]\n"
142       "\t2\tD1 @ 25 fps (PAL)\n"
143       "\t3\t720P @ 60 fps\n"
144       "\t4\t720P @ 50 fps\n"
145       "\t5\t1080I @ 30 fps [Not supported for DM365]\n"
146       "\t6\t1080I @ 25 fps [Not supported for DM365]\n"
147       "You must supply at least a video or a speech file or both\n"
148       "with appropriate extensions for the file formats.\n\n");
149 }
150

核心部分:参数解析的时候分短选项和长选项,那么shortOptions与longOptions就对应与两者,

其中shortOptions选项中如果加了“:”冒号,那么就需要带参数,而longOptions中通过“ required_argument”

与“  no_argument“来进行区分,最后把这两个参数传递给getopt_long函数就能逐一返回一个个选项,再根据选项

得到对应的参数,并将其存放在结构体中,整个过程就这样了;

151 /*******************************
152  * parseArgs
153  ******************************/
154 static Void parseArgs(Int argc, Char *argv[], Args *argsp)
155 {
156     const Char shortOptions[] = "s:v:y:r:b:xlkt:oih";
157     const struct option longOptions[] = {
158         {"speechfile",       required_argument, NULL, 's'},
159         {"videofile",        required_argument, NULL, 'v'},
160         {"display_standard", required_argument, NULL, 'y'},
161         {"resolution",       required_argument, NULL, 'r'},
162         {"videobitrate",     required_argument, NULL, 'b'},
163         {"svideo",           no_argument,       NULL, 'x'},
164         {"linein",           no_argument,       NULL, 'l'},
165         {"keyboard",         no_argument,       NULL, 'k'},
166         {"time",             required_argument, NULL, 't'},
167         {"osd",              no_argument,       NULL, 'o'},
168         {"interface",        no_argument,       NULL, 'i'},
169         {"help",             no_argument,       NULL, 'h'},
170         {0, 0, 0, 0}
171     };
172
173     Int     index;
174     Int     c;
175     Char    *extension;
176
177     for (;;) {
178         c = getopt_long(argc, argv, shortOptions, longOptions, &index);
179
180         if (c == -1) {
181             break;
182         }
183
184         switch (c) {
185             case 0:
186                 break;
187
188             case 's':
189                 extension = rindex(optarg, '.');
190                 if (extension == NULL) {
191                     fprintf(stderr, "Speech file without extension: %s\n",
192                             optarg);
193                     exit(EXIT_FAILURE);
194                 }
195
196                 argsp->speechEncoder =
197                     getCodec(extension, engine->speechEncoders);
198
199                 if (!argsp->speechEncoder) {
200                     fprintf(stderr, "Unknown speech file extension: %s\n",
201                             extension);
202                     exit(EXIT_FAILURE);
203                 }
204                 argsp->speechFile = optarg;
205
206                 break;

....


305             case 't':

306                 argsp->time = atoi(optarg);
307                 break;
308
309             case 'o':
310                 argsp->osd = TRUE;
311                 break;
312
313             case 'i':
314                 argsp->interface = TRUE;
315                 break;
316
317             case 'h':
318                 usage();
319                 exit(EXIT_SUCCESS);
320
321             default:
322                 usage();
323                 exit(EXIT_FAILURE);
324         }
325     }
326
327     if (argsp->videoInput != Capture_Input_SVIDEO) {
328         if (argsp->videoStd == VideoStd_D1_NTSC || argsp->videoStd == VideoStd_D1_PAL ) {
329             argsp->videoInput = Capture_Input_COMPOSITE;
330         } else {
331             argsp->videoInput = Capture_Input_COMPONENT;
332         }
333     }
334
335     /* Need at least one file to decode and only one sound file */
336     if (!argsp->videoFile && !argsp->speechFile) {
337         usage();
338         exit(EXIT_FAILURE);
339     }

340 }


第三部分:主函数调用部分

388 /********************************
389  * main
390  *******************************/
391 Int main(Int argc, Char *argv[])
392 {
393     Args                args                = DEFAULT_ARGS;
426     /* Parse the arguments given to the app and set the app environment */
427     parseArgs(argc, argv, &args);
428 }

注意:头文件为 #include <getopt.h>,man 到的信息如下:

www@linux:~/abs_guide/chapter3$ man -k getopt_long
getopt_long (3)      - Parse command-line options
getopt_long_only (3) - Parse command-line options