delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp-workers/2001/05/30/12:09:10

From: "Mark E." <snowball3 AT bigfoot DOT com>
To: djgpp-workers AT delorie DOT com
Date: Tue, 29 May 2001 23:53:26 -0400
MIME-Version: 1.0
Subject: getopt docs
Message-ID: <3B143676.30057.2E3B40@localhost>
X-mailer: Pegasus Mail for Win32 (v3.12c)
Reply-To: djgpp-workers AT delorie DOT com

I've revised the docs for getopt to cover the changes to bring getopt() into 
Posix compliance.

@node getopt, misc
@subheading Syntax

@example
#include <unistd.h>

int getopt(int argc, char * const *argv, const char *options);
extern char *optarg;
extern int optind, opterr, optopt;
@end example

@subheading Description

Parse options from the command line.  @var{options} is a string of
valid option characters.  If a given option takes an argument, that
character should be followed by a colon.

For each valid switch, this function sets @code{optarg} to the argument
(if the switch takes one), sets @code{optind} to the index in @var{argv}
that it is using, sets @code{optopt} to the option letter found, and
returns the option letter found.

If an unexpected option is found, a question mark (@samp{?}) is returned.  
If an option argument is missing, a colon (@samp{:}) is returned if the
first character in @var{options} is a colon, otherwise a question mark is
returned.  In both cases, if @code{opterr} is nonzero and the first character
in @var{options} is not a colon, an error message is printed to stderr.

The example below shows how @samp{?} can still be used as an option
(e.g., to request a summary of program usage) in addition to flagging
an unexpected option and a missing argument.

@subheading Return Value

The option character is returned when found.  -1 is returned when there are 
no
more options.  A colon (@samp{:}) is returned when an option argument is
missing and the first character in @var{options} is a colon.  A question mark
(@samp{?}) is returned when an invalid option is found or an option argument
is missing and the first character in @var{options} is not a colon.

@subheading Portability

@portability !ansi, posix

@subheading Example

@example
int c;
opterr = 0;
while ((c=getopt(argc, argv, ":?vbf:")) != -1)
@{
  switch (c)
  @{
    case 'v':
      verbose_flag ++;
      break;
    case 'b':
      binary_flag ++;
      break;
    case 'f':
      output_filename = optarg;
      break;
    case ':':
      printf("Missing argument %c\n", optopt);
      usage();
      exit(1);
    case '?':
      if (optopt == '?') @{
        usage();
        exit(0);
     @} else @{
        printf("Unknown option %c\n", optopt);
        usage();
        exit(1);
     @}
  @}
@}
@end example

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019