Linux编程学习——getopt典型应用

本文介绍了一个使用getopt()处理命令行选项的应用实例。该程序展示了如何解析命令行参数,并将这些参数存储在一个全局结构中以便于后续使用。支持的选项包括:不生成索引、指定输出语言、设置输出文件名及增加诊断信息的详细程度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/* getopt_demo - demonstrate getopt() usage
*
* This application shows you one way of using getopt() to
* process your command-line options and store them in a
* global structure for easy access.
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

/* doc2html supports the following command-line arguments:
*
* -I - don't produce a keyword index
* -l lang - produce output in the specified language, lang
* -o outfile - write output to outfile instead of stdout
* -v - be verbose; more -v means more diagnostics
* additional file names are used as input files
*
* The optString global tells getopt() which options we
* support, and which options have arguments.
*/
struct globalArgs_t {
int noIndex; /* -I option */
char *langCode; /* -l option */
const char *outFileName; /* -o option */
FILE *outFile;
int verbosity; /* -v option */
char **inputFiles; /* input files */
int numInputFiles; /* # of input files */
} globalArgs;

static const char *optString = "Il:o:vh?";

/* Display program usage, and exit.
*/
void display_usage( void )
{
puts( "doc2html - convert documents to HTML" );
/* ... */
exit( EXIT_FAILURE );
}

/* Convert the input files to HTML, governed by globalArgs.
*/
void convert_document( void )
{
printf("InputFiles:%d\n",globalArgs.numInputFiles);
/* ... */
}

int main( int argc, char *argv[] )
{
int opt = 0;

/* Initialize globalArgs before we get to work. */
globalArgs.noIndex = 0; /* false */
globalArgs.langCode = NULL;
globalArgs.outFileName = NULL;
globalArgs.outFile = NULL;
globalArgs.verbosity = 0;
globalArgs.inputFiles = NULL;
globalArgs.numInputFiles = 0;

/* Process the arguments with getopt(), then
* populate globalArgs.
*/
opt = getopt( argc, argv, optString );
while( opt != -1 ) {
switch( opt ) {
case 'I':
globalArgs.noIndex = 1; /* true */
break;

case 'l':
globalArgs.langCode = optarg;
break;

case 'o':
/* This generates an "assignment from
* incompatible pointer type" warning that
* you can safely ignore.
*/
globalArgs.outFileName = optarg;
break;

case 'v':
globalArgs.verbosity++;
break;

case 'h': /* fall-through is intentional */
case '?':
display_usage();
break;

default:
/* You won't actually get here. */
break;
}

printf("optind=%d\n",optind);
opt = getopt( argc, argv, optString );
}

globalArgs.inputFiles = argv + optind;
globalArgs.numInputFiles = argc - optind;
printf("argc=%d\n",argc);
printf("optind=%d\n",optind);
convert_document();

return EXIT_SUCCESS;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值