mymain(1) -- commandline application template.

0.2.4

NAME
{program_name} - {program_description}.

SYNOPSIS
{program_name} [-ahHdDvVz] [-f] [-g value] [-o output] [arg ...]

It is possible to have whitespace between a command line option and its parameter.

DESCRIPTION
{program_name} ...

Initialization
...

Options
{program_name} can be executed with the following options:

-a : print author information
-h : short help
-H : manual page
-f : a flag
-g val: a value; may not be zero
-o out: output filename
-d+ : debug information (-d stdout, -D stderr)
-v+ : be verbose (-v stdout, -V stderr)
-v : report ...
-vv : also report ...
-vvv : also report ...
-z : suppress informative messages
-- : end option section

If you want to use - as the first filename, -- must precede it to end the option section. When a filelist from standard input is used,- cannot be used for filename.

Option -v increases the verbosity level, whereas option -z lowers it, so -vz is effectively a no-operation, and -Vz can be used to direct the normal messages to standard error (stderr).

Processing
{program_name} ...

Error messages
Error messages report on invalid options and invalid option values. ...

Program exit status
When an invalid option, or invalid option value is specified, or when a file cannot be properly processed, the program stops and issues an error message. The failure is reflected in the program exit status (see DIAGNOSTICS below).

ENVIRONMENT
none.

FILES
{program_name} uses the following files:

{afile} ...

DIAGNOSTICS
{program_name} can return the following exit values:

  1. success: program execution has been successfully completed,
  2. commandline error: an invalid option, or option value is specified,
  3. processing error: a file could not be opened or closed, an error occurred while writing to an output file,
  4. interruption: the user interrupted the program,
  5. internal error: an unexpected situation in program behaviour occurred.

SEE ALSO
mymain -- commandline application template

LIMITATIONS
(to do)

BUGS
(to be determined.)

AUTHOR
Martin J. Moene <moene@biophys.LeidenUniv.nl>

Huygens Laboratorium
Niels Bohrweg 2
2333 CA Leiden
The Netherlands

The latest distribution can be downloaded from:
http://fwneld.LeidenUniv.nl/~moene/templates/

Generated on Thu Jan 30 10:06:37 2003 for mymain by doxygen 1.3-rc2


File Index

mymain File List

Here is a list of all documented files with brief descriptions:
tools.h [code]
version.h [code]
XGetopt.h [code]
Generated on Thu Jan 30 10:06:37 2003 for mymain by doxygen 1.3-rc2


Module Index

mymain Modules

Here is a list of all modules:
  • mymain -- commandline application template
  • tools -- error handling and filename tools
  • getopt -- commandline option handling
Generated on Thu Jan 30 10:06:39 2003 for mymain by doxygen 1.3-rc2


mymain -- commandline application template

Detailed Description

mymain -- commandline application template.

mymain.cpp is a template for a commandline program. It contains a main() with the often recurring structure to:

  • scan the commandline options, using getopt()
  • print a usage screen, function usage()
  • print a longer description, function manual()
  • loop through the non-option arguments and
  • optionally select arguments interactively, using pick()
  • perform the program's specific processing, using action()
The template uses several functions from module tools -- error handling and filename tools like error() and pick().

Namespaces

namespace | std

Functions

int | action (int flag, int value, const char *arg)
the heart of the application.

int | author (int status, FILE *stream)
print author contact information.

int | usage (int status, FILE *stream)
show intent and usage of application.

int | manual (int status, FILE *stream)
print a description of this program.

int | main (int argc, char *argv[])
process commandline arguments.

Function Documentation

int action | ( | int | flag,
 |  | int | value,
 |  | const char * | arg
 | ) | [static]

the heart of the application.

action() performs the actual work for this application. The signature of this function depends verymuch on the things you want to do. For example, option flags and values may be kept global and all non-option arguments may have to be used together instead of separately.

Parameters:
flag | 'a flag'
value | 'a value'
arg | current commandline argument
Returns:
application (exit) status, see E_OK
Examples:
main.cpp.

int author | ( | int | status,
 |  | FILE * | stream
 | ) | [static]

print author contact information.

author() prints author contact information.

Parameters:
status | status to return
stream | stream to print on
Returns:
application (exit) status, see E_OK
Examples:
author.cpp, and main.cpp.

int main | ( | int | argc,
 |  | char * | argv[]
 | ) |

process commandline arguments.

main() first processes the options supplied on the commandline using getopt(). Then it performs action() on each non-option argument on the commandline. If there are no arguments, main() calls usage() to print an overview of this application.

It may not always be appropriate to loop through the non-option arguments, but instead use all remaining arguments together. In this case, the for loop below must be changed or removed.

 for ( int i = optind; i < argc; i++ )
 {
    if ( !pick( optInteractive, argv[i] ) )
         continue;

    int status = action( optFlag, optValue, argv[i] );

    if ( E_OK != status )
         return status;
 }

Parameters:
argc | argument count
argv | argument vector
Returns:
application exit status, see E_OK
See also:
getopt(), pick(), usage()
Examples:
main-simple.cpp, and main.cpp.

int manual | ( | int | status,
 |  | FILE * | stream
 | ) | [static]

print a description of this program.

manual() prints a short manual page for this application.

Parameters:
status | status to return
stream | stream to print on
Returns:
application (exit) status, see E_OK
See also:
usage()
Examples:
main.cpp, and manual.cpp.

int usage | ( | int | status,
 |  | FILE * | stream
 | ) | [static]

show intent and usage of application.

usage() prints a short description of intent and usage of this application

Parameters:
status | status to return
stream | stream to print on
Returns:
application (exit) status, see E_OK
See also:
manual()
Examples:
main.cpp, and usage.cpp.

Variable Documentation

const char* title

Initial value:

   "{program}  " VERSION_STRING "  {program_description.}\n"
   "Copyright (C) 2003, {copyright_owner}. All rights reserved.\n"
   "{project_name} is free software.  See the file Copying for copying permission."

Generated on Thu Jan 30 10:06:39 2003 for mymain by doxygen 1.3-rc2


tools -- error handling and filename tools

Detailed Description

tools -- error handling and filename tools.

Error handling -- error messages can be formatted and print with error(). The programname as set with setprogname() precedes the message. Error messages are printed to the stderr stream.

General messages -- function message() is meant to format and print normal messages, for example to trace the program's normal processing. A message also specifies a level and the message is only printed, if its level is equal or lower than the current message verbosity level as set with setmsglevel(). Messages are printed to the stream as set with setmsgfile(), default it is stdout.

Debug messages -- function debug() is meant to format and print debug messages, for example to trace the program's data handling. A debug message also specifies a level and the message is only printed, if its level is equal or lower than the current debug message verbosity level as set with setdbglevel(). Messages are printed to the stream as set with setdbgfile(), default it is stdout.

Filenames -- parts of a filename path can be obtained with basename(), dirname() and extname(). Function exist() tells if the specified filename exists.

User interaction -- funtion prompt() lets you request a user to supply a non-empty string. With pick() you ask a user to accept or reject its argument. ttyin() reads a single character from the terminal.

Several tools functions are used in mymain.

Enumerations

enum | { E_OK, E_OPT, E_PS, E_INT, E_ITL }
application return codes. More...

enum | { MSG_L0, MSG_L1, MSG_L2 }
application message level codes. More...

enum | { DBG_L0, DBG_L1, DBG_L2 }
application debug level codes. More...

Functions

const char * | getprogname ()
return the program's name as set with setprogname().

void | setprogname (const char *name)
set the program's name as used with error() etc.

int | getmsglevel ()
get the current message verbosity level.

void | setmsglevel (int level)
set the message verbosity level.

FILE * | getmsgfile ()
get the current file messages will be written to.

void | setmsgfile (FILE *file)
set the file to write messages to.

int | getdbglevel ()
get the current debug message verbosity level.

void | setdbglevel (int level)
set the debug message verbosity level.

FILE * | getdbgfile ()
get the current file debug messages are written to.

void | setdbgfile (FILE *file)
set the file to write the debug messages to.

int | error (int status, const char *format...)
format and print error message, return status.

int | debug (int level, const char *format...)
format and print debug message, if level permits.

int | message (int level, const char *format...)
format and print message, if level permits.

const char * | dirname (const char *pathname)
return directory part of pathname.

const char * | basename (const char *pathname)
return filename without directory part and extension.

const char * | extname (const char *pathname)
return extension of filename.

int | exist (const char *filename)
tell if specified filename exists.

string | prompt (const char *ps)
prompt for non-empty string input.

int | pick (int isInteractive, const char *arg, const char *set)
select or skip argument.

int | ttyin ()
read a character from the terminal.

Enumeration Type Documentation

anonymous enum

application return codes.

Enumeration values:
E_OK | fine
E_OPT | commandline option/argument error
E_PS | processing error
E_INT | user interrupted program
E_ITL | internal/unrecognized error

anonymous enum

application message level codes.

Enumeration values:
MSG_L0 | level 0, defult on
MSG_L1 | level 1
MSG_L2 | level 2

anonymous enum

application debug level codes.

Enumeration values:
DBG_L0 | level 0, default on
DBG_L1 | level 1
DBG_L2 | level 2

Function Documentation

const char* basename ( const char * pathname )

return filename without directory part and extension.

basename() returns the filename part of the given path without the extension. The returned string does not contain a trailing slash.

If you specify a pathname of NULL, the program's path is used as set with setprogname().

Note:
basename() returns a static buffer, so you must use its contents before the next call to basename().
Parameters:
pathname path or NULL
Returns:
string with basename
See also:
dirname(), extname()
Examples:
main-simple.cpp, and main.cpp.

int debug | ( | int | level,
 |  | const char * | format...
 | ) |

format and print debug message, if level permits.

debug() formats and prints the message if the specified level is equal or less than the current debug level. format is a printf format string, optionally followed by arguments.

The message has the following format:

[progname: ]message[: system-message]\n

progname is included when a colon starts the format and it has been set via setprogname(); system-message is included when the format string ends with a colon (:).

debug() returns the specified level.

Parameters:
level | this message's level
format | a printf format string, optionally followed by arguments
Returns:
level
See also:
setprogname(), getdbglevel(), setdbglevel(), getdbgfile(), setdbgfile()
Examples:
main.cpp.

const char* dirname ( const char * pathname )

return directory part of pathname.

dirname() returns the directory part of the given path. The returned string does not contain a trailing slash.

If you specify a pathname of NULL, the program's path is used as set with setprogname().

Note:
dirname() returns a static buffer, so you must use its contents before the next call to dirname().
Parameters:
pathname path or NULL
Returns:
string with directory part
See also:
basename(), extname()

int error | ( | int | status,
 |  | const char * | format...
 | ) |

format and print error message, return status.

error() formats and prints and error message. format is a printf format string, optionally followed by arguments.

The error message has the following format:

[progname: ]message[: system-message]\n

progname is included when it has been set via setprogname(); system-message is included when the format string ends with a colon (:).

error() returns the specified status.

Parameters:
status | the error status to return, see E_OK
format | a printf format string, optionally followed by arguments
Returns:
application exit status
See also:
setprogname()
Examples:
main-simple.cpp, and main.cpp.

int exist ( const char * filename )

tell if specified filename exists.

exist() returns true if the specified filename is "-" (stdin) or exists as diskfile, exist() returns false otherwise.

Parameters:
filename name of file to check for
Returns:
1, 0 (exists, not exists)
See also:
prompt()

const char* extname ( const char * pathname )

return extension of filename.

extname() returns the extension part of the given path without a dot.

If you specify a pathname of NULL, the program's path is used as set with setprogname().

Note:
extname() returns a static buffer, so you must use its contents before the next call to extname().
Parameters:
pathname path or NULL
Returns:
string with extension
See also:
dirname(), basename()

FILE* getdbgfile ( )

get the current file debug messages are written to.

getdbgfile() returns the current file to write the debug messages to. Default it is stdout.

Returns:
current file to write debug messages to
See also:
getdbglevel(), setdbglevel(), getdbgfile(), debug()

int getdbglevel ( )

get the current debug message verbosity level.

getdbglevel() returns the current level for debug messages to be printed.

Returns:
current debug verbosity level
See also:
setdbglevel(), getdbgfile(), setdbgfile(), debug()

FILE* getmsgfile ( )

get the current file messages will be written to.

getmsgfile() returns the current file to write the messages to. Default it is stdout.

Returns:
current file to write messages to
See also:
setmsgfile(), getmsglevel(), setmsglevel(), message()
Examples:
main.cpp.

int getmsglevel ( )

get the current message verbosity level.

getmsglevel() returns the current level for messages to be printed.

Returns:
current verbosity level
See also:
setmsglevel(), getmsgfile(), setmsgfile(), message()
Examples:
main.cpp.

const char* getprogname ( )

return the program's name as set with setprogname().

getprogname() returns the program's name as it has been set with setprogname(). If setprogname() has not been called, getprogname() returns NULL.

Returns:
the name of the program, or NULL
See also:
setprogname(), error(), message(), debug()
Examples:
usage.cpp.

int message | ( | int | level,
 |  | const char * | format...
 | ) |

format and print message, if level permits.

message() formats and print the specified message if its level is equal or less than the current verbosity level as set with setmsglevel(). format is a printf format string, optionally followed by arguments.

The message has the following format:

[progname: ]message[: system-message]\n

progname is included when a colon starts the format and it has been set via setprogname(); system-message is included when the format string ends with a colon (:).

message() returns the specified level.

Parameters:
level | this message's level
format | a printf format string, optionally followed by arguments
Returns:
level
See also:
setprogname(), getmsglevel(), setmsglevel(), getmsgfile(), setmsgfile()
Examples:
main.cpp.

int pick | ( | int | isInteractive,
 |  | const char * | arg,
 |  | const char * | set
 | ) |

select or skip argument.

If isInteractive is true, pick() writes its argument arg followed by a question mark to stderr and waits for a one-key response. If the response is a member of the supplied or default set, pick returns 1, for all other values, it returns 0.

If isInteractive is false, pick() returns true immediately, without prompting.

Parameters:
isInteractive | select interactively
arg | argument to use or skip
set | string with response characters to accept argument [yY]
Returns:
0, 1 (skip, use)
See also:
prompt()
Examples:
main.cpp.

string prompt ( const char * ps )

prompt for non-empty string input.

prompt() issues the prompt ps and returns the user's response. prompt() skips leading whitespace and includes all input to the end of the line.

prompt() keeps prompting until a non-empty resonse is provided.

Parameters:
ps prompt string
Returns:
response string
See also:
pick()

void setdbgfile ( FILE * file )

set the file to write the debug messages to.

setdbgfile() sets the file to write the debug messages to. Default it is stdout.

Parameters:
file file to write debug messages to [stdout]
See also:
getdbglevel(), setdbglevel(), getdbgfile(), debug()
Examples:
main.cpp.

void setdbglevel ( int level )

set the debug message verbosity level.

setdbglevel() sets the level for debug messages to be printed. Debug messages with a level equal or less than the current verbosity level as set with setdbglevel() will be printed. The debug level is default 0.

Parameters:
level debug verbosity level to set [0]
See also:
getdbglevel(), getdbgfile(), setdbgfile(), debug()
Examples:
main.cpp.

void setmsgfile ( FILE * file )

set the file to write messages to.

setmsgfile() sets the file to write the messages to. Default it is stdout.

Parameters:
file file to write messages to [stdout]
See also:
setmsglevel(), getmsgfile(), getmsgfile(), message()
Examples:
main.cpp.

void setmsglevel ( int level )

set the message verbosity level.

setmsglevel() sets the level for messages to be printed. Messages with a level equal or less than the current verbosity level as set with setmsglevel() will be printed. The message level is default 0.

Parameters:
level verbosity level to set [0]
See also:
getmsglevel(), getmsgfile(), setmsgfile(), message()
Examples:
main.cpp.

void setprogname ( const char * name )

set the program's name as used with error() etc.

setprogname() sets the program's name to the one specified. It is used with error(), message() and debug().

Parameters:
name the name of the program
Returns:
none
See also:
getprogname(), error(), message(), debug()
Examples:
main-simple.cpp, and main.cpp.

int ttyin ( )

read a character from the terminal.

ttyin() reads a single character from the terminal, echoes and returns it.

Returns:
character read
See also:
pick()

Generated on Thu Jan 30 10:06:39 2003 for mymain by doxygen 1.3-rc2


getopt -- commandline option handling

Detailed Description

getopt -- parse command line options

Functions

int | getopt (int argc, char *argv[], char *optstring)
parse command line options

Variables

char * | optarg
optarg points to the current option's argument.

int | optind = 0
argv index of next argument to process.

int | opterr
opterr is not used by this version of getopt().

Function Documentation

int getopt | ( | int | argc,
 |  | char * | argv[],
 |  | char * | optstring
 | ) |

parse command line options

The getopt() function parses the command line arguments. Its arguments argc and argv are the argument count and array as passed into the application on program invocation. In the case of Visual C++ programs, argc and argv are available via the variables __argc and __argv (double underscores), respectively. getopt() returns the next option letter in argv that matches a letter in optstring.

optstring is a string of recognized option letters; if a letter is followed by a colon, the option is expected to have an argument that may or may not be separated from it by white space. optarg is set to point to the start of the option argument on return from getopt().

Option letters may be combined, e.g., "-ab" is equivalent to "-a -b". Option letters are case sensitive.

getopt() places in the external variable optind the argv index of the next argument to be processed. optind is initialized to 0 before the first call to getopt().

When all options have been processed (i.e., up to the first non-option argument), getopt() returns EOF, optarg will point to the argument, and optind will be set to the argv index of the argument. If there are no non-option arguments, optarg will be set to NULL.

The special option "--" may be used to delimit the end of the options; EOF will be returned, and "--" (and everything after it) will be skipped.

Returns:
For option letters contained in the string optstring, getopt() will return the option letter. getopt() returns a question mark (?) when it encounters an option letter not included in optstring. EOF is returned when processing is finished.
Author:
Hans Dietrich <hdietrich2@hotmail.com>

Bug:
  • Long options are not supported.
  • The GNU double-colon extension is not supported.
  • The environment variable POSIXLY_CORRECT is not supported.
  • The + syntax is not supported.
  • The automatic permutation of arguments is not supported.
  • This implementation of getopt() returns EOF if an error is encountered, instead of -1 as the latest standard requires.
Example:

 BOOL CMyApp::ProcessCommandLine(int argc, char *argv[])
 {
     int c;

     while ((c = getopt(argc, argv, "aBn:")) != EOF)
     {
           switch (c)
           {
               case 'a':
                   TRACE(_T("option a\n"));
                   //
                   // set some flag here
                   //
                   break;

               case 'B':
                   TRACE( _T("option B\n"));
                   //
                   // set some other flag here
                   //
                   break;

               case 'n':
                   TRACE(_T("option n: value=%d\n"), atoi(optarg));
                   //
                   // do something with value here
                   //
                   break;

               case '?':
                   TRACE(_T("ERROR: illegal option %s\n"), argv[optind-1]);
                   return FALSE;
                   break;

               default:
                   TRACE(_T("WARNING: no handler for option %c\n"), c);
                   return FALSE;
                   break;
           }
     }
     //
     // check for non-option args here
     //
     return TRUE;
 }
Examples:
main.cpp.

Variable Documentation

char* optarg

optarg points to the current option's argument.

On return from getopt(), optarg is set to point to the start of the option argument. If there are no non-option arguments, optarg will be set to NULL.

int opterr

opterr is not used by this version of getopt().

This version of getopt() does not fill opterr.

int optind = 0

argv index of next argument to process.

getopt() places in the external variable optind the argv index of the next argument to be processed. optind is initialized to 0 before the first call to getopt().

Generated on Thu Jan 30 10:06:39 2003 for mymain by doxygen 1.3-rc2


Example Index

mymain Examples

Here is a list of all examples:
  • author.cpp
  • main-simple.cpp
  • main.cpp
  • manual.cpp
  • usage.cpp
Generated on Thu Jan 30 10:06:40 2003 for mymain by doxygen 1.3-rc2


Example Documentation

author.cpp

This example shows a typical setup of a author() function.

static int author( int status, FILE *stream )
{
   (void) fprintf( stream,
      "\n"
      " author: Martin J. Moene\n"
      "         Huygens Laboratorium\n"
      "         Niels Bohrweg 2\n"
      "         2333 CA Leiden\n"
      "         The Netherlands\n"
      "\n"
      "phoneto: +31-71-5275960\n"
      " mailto: moene@biophys.LeidenUniv.nl\n"
   );

   return status;
}
Generated on Thu Jan 30 10:06:37 2003 for mymain by doxygen 1.3-rc2


Example Documentation

main-simple.cpp

This example shows how error() can be used.

#include <stdio>                // for EXIT_FAILURE
#include "tools.h"              // for setprogname(), error()

int main( int argc, char *argv[] )
{
   setprogname( basename( argv[0] ) );

   if ( argc <= 1 )
      return error( EXIT_FAILURE, "input output" );

   // ...
}
Generated on Thu Jan 30 10:06:37 2003 for mymain by doxygen 1.3-rc2


Example Documentation

main.cpp

This example shows a typical setup of a main() function.

#include <io.h>                 // isatty()
#include <stdio.h>              // for EXIT_FAILURE
#include "version.h"            // for VERSION_STRING
#include "tools.h"              // for setprogname(), error()

const char *title =
   "{program}  " VERSION_STRING "  {program_description.}\n"
   "Copyright (C) 2003, {copyright_owner}. All rights reserved.\n"
   "{project_name} is free software.  See the file Copying for copying permission.";

static char *outName        = "stdout"; // option -o: output-name
static FILE *outFile        =  stdout;  //            output-file

static int   optFlag        = 0;  // option -f: a flag
static int   optValue       = 0;  // option -g: a value

static int   optInteractive = 0;  // option -i: select arguments interactively
static int   optDebug       = 0;  // option -d/D: debug
static int   optVerbose     = 0;  // option -v/V: verbose

static int   action    ( int flag, int value, const char *name, FILE *file, const char *arg /* args... */ );
static int   subaction1( );
static int   subaction2( );
static int   subaction3( );

static int   author    ( int status, FILE *stream );
static int   usage     ( int status, FILE *stream );
static int   manual    ( int status, FILE *stream );

/*
 * main - handle commandline.
 */

int main( int argc, char *argv[] )
{
#if defined( __unix__ )
   setprogname( basename( argv[0] ) );
#else
   setprogname( basename( strlwr( argv[0] ) ) );
#endif

   /*
    * if no arguments specified, print usage:
    */

   if ( argc <= 1 )
      return usage( E_OK, stdout );

   /*
    * handle options:
    */

   int c;
   while ( EOF != (c = getopt(argc, argv, "ahHdDvVzifg:o:") ) )
   {
      switch ( c )
      {
         case 'a':                              // -a: author information
            return author( E_OK, stdout );

         case 'h':                              // -h: help
            return usage( E_OK, stdout );

         case 'H':                              // -H: manual
            return manual( E_OK, stdout );

         case 'i':                              // -i: select arguments interatively
            ++optInteractive;
            break;

         case 'f':                              // -f: a flag
            ++optFlag;
            break;

         case 'g':                              // -g value: a value
            if ( 0 == ( optValue = atoi( optarg ) ) )
               return error( E_OPT, "invalid value for option -%c (%s)", c, optarg );
            break;

         case 'o':                              // -o output: output file
            if ( 0 == ( outName = optarg ) )
               return error( E_OPT, "output filename expected for option -%c", c );

            if ( 0 == ( outFile = fopen( outName, "w" ) ) )
               return error( E_OPT, "cannot open output file '%s':", outName );
            break;

#if defined(DEBUG)
         case 'D':                              // -D: debug (stderr)
            setdbgfile( stderr );               //     fall through

         case 'd':                              // -d: debug (stdout)
            setdbglevel( ++optDebug );
            break;
#else
         case 'D':                              // -D: debug (stderr)
         case 'd':                              // -d: debug (stdout)
            return error( E_OPT, "option -%c: debugging not supported in this build", c );
            break;
#endif
         case 'V':                              // -V: verbose (stderr)
            setmsgfile( stderr );               //     fall through

         case 'v':                              // -v: verbose (stdout)
            setmsglevel( ++optVerbose );
            break;

         case 'z':                              // -z: suppress normal messages
            setmsglevel( --optVerbose );
            break;

         case '?':                              // (option not recognized)
            return error( E_OPT, "unrecognized option %s\n", argv[optind-1] );

         default:                               // (unhandled return value)
            return error( E_OPT, "no handler for option -%c\n", c);
      }
   }

   debug( DBG_L1, "debug: options handled" );

   /*
    * if no arguments specified, print usage:
    */

   if ( optind >= argc )
      return usage( E_OK, stdout );

   /*
    * handle commandline arguments:
    */

   message( MSG_L0, "%s\n", title );

   debug( DBG_L1, "debug: processing commandline arguments" );

   for ( int i = optind; i < argc; i++ )
   {
      debug( DBG_L2, "   argv[%d]: '%s'", i, argv[i] );

      if ( !pick( optInteractive, argv[i] ) )
         continue;

      int status = action( optFlag, optValue, outName, outFile, argv[i] );

      if ( E_OK != status )
         return status;
   }

   debug( DBG_L1, "debug: finishing program" );

   if ( outFile && !isatty( fileno( outFile ) )&& EOF == fclose( outFile ) )
      return error( E_PS, "cannot close output file '%s':", outName );

   return E_OK;
}

static int action( int flag, int value, const char *name, FILE *file, const char *arg /* args... */ )
{
   if ( getmsglevel() >= MSG_L1 )
      fprintf( getmsgfile(), "[%s]", arg );

   return subaction1()
       || subaction2()
       || subaction3() ? E_PS : E_OK;
}

static int subaction1( ) { message( MSG_L2, "\nsubaction1()"   ); return E_OK; }
static int subaction2( ) { message( MSG_L2,   "subaction2()"   ); return E_OK; }
static int subaction3( ) { message( MSG_L2,   "subaction3()\n" ); return E_OK; }
Generated on Thu Jan 30 10:06:38 2003 for mymain by doxygen 1.3-rc2


Example Documentation

manual.cpp

This example shows a typical setup of a manual() function.

static int manual( int status, FILE *stream )
{
   (void) fprintf( stream,
"NAME\n"
"       {program_name} - {program_description}.\n"
"\n"
"\n"
"SYNOPSIS\n"
#if defined(DEBUG)
"      {program_name} [-ahHdDivVz] [-f] [-g value] [-o outout] [--] [-] [arg ...]\n"
#else
"      {program_name} [-ahHivVz] [-f] [-g value] [-o outout] [--] [-] [arg ...]\n"
#endif
"\n"
"      It is possible to have whitespace between a command line option\n"
"      and its parameter.\n"
"\n"
"\n"
"DESCRIPTION\n"
"      {program_name} ...\n"
"\n"
"   Options\n"
"      {program_name} can be executed with the following options:\n"
"\n"
"      -a       : print author information\n"
"      -h       : short help\n"
"      -H       : manual page\n"
"      -f       : a flag\n"
"      -g value : a value; may not be zero\n"
"      -i       : select arguments interactively\n"
"      -o output: output filename\n"
#if defined(DEBUG)
"      -d+      : debug information (-d stdout, -D stderr)\n"
#endif
"      -v+      : be verbose (-v stdout, -V stderr)\n"
"      -v       : report ...\n"
"      -vv      : also report ...\n"
"      -vvv     : also report ...\n"
"      -z       : suppress informative messages\n"
"      --       : end option section\n"
"\n"
"      If you want to use - as the first filename, -- must precede it to\n"
"      end the option section. When a filelist from standard input is used,\n"
"      - cannot be used for filename.\n"
"\n"
"      Option -v increases the verbosity level, while option -z lowers it,\n"
"      so -vz is effectively a no-operation, and -Vz can be used to direct\n"
"      the normal messages to standard error (stderr).\n"
"\n"
"   Processing\n"
"      {program_name} ...\n"
"\n"
"   Error messages\n"
"      Error messages report on invalid options and invalid option values.\n"
"      ...\n"
"\n"
"   Program exit status\n"
"      When an invalid option, or invalid option value is specified, or\n"
"      when a file cannot be properly processed, or a PVCAM error occurs,\n"
"      the program stops and issues an error message. The failure is reflected\n"
"      in the program exit status (see DIAGNOSTICS below).\n"
"\n"
"\n"
"ENVIRONMENT\n"
"      none.\n"
"\n"
"\n"
"FILES\n"
"      {program_name} uses the following files:\n"
"\n"
"      {afile}  ...\n"
"\n"
"\n"
"DIAGNOSTICS\n"
"      {program_name} can return the following exit values:\n"
"\n"
"      0 success: program execution has been successfully completed,\n"
"      1 commandline error: an invalid option, or option value is specified,\n"
"      2 processing error: a file could not be opened or closed, an error\n"
"        occurred while writing to an output file,\n"
"      3 interruption: the user interrupted the program,\n"
"      4 internal error: an unexpected situation in program behaviour occurred.\n"
"\n"
"\n"
"SEE ALSO\n"
"      (none)\n"
"\n"
"\n"
"LIMITATIONS\n"
"      (to do)\n"
"\n"
"\n"
"BUGS\n"
"      (to be determined.)\n"
"\n"
"\n"
"EXAMPLES\n"
"      (to do)\n"
"\n"
"\n"
"AUTHOR\n"
"      Martin J. Moene (moene@biophys.LeidenUniv.nl)\n"
"\n"
"      Huygens Laboratorium\n"
"      Niels Bohrweg 2\n"
"      2333 CA Leiden\n"
"      The Netherlands\n"
   );

   return status;
}
Generated on Thu Jan 30 10:06:38 2003 for mymain by doxygen 1.3-rc2


Example Documentation

usage.cpp

This example shows a typical setup of a usage() function.

static int usage( int status, FILE *stream )
{
   (void) fprintf( stream,
      "%s\n\n"
#if defined(DEBUG)
      "Usage: %s [-ahHdDvVz] [-f] [-g value] [-o output] [--] [-] [arg ...]\n"
#else
      "Usage: %s [-ahHvVz] [-f] [-g value] [-o output] [--] [-] [arg ...]\n"
#endif
      "-a       : print author information\n"
      "-h       : this help\n"
      "-H       : manual page\n"
      "-f       : a flag\n"
      "-g value : a value; may not be zero\n"
      "-i       : select arguments interactively\n"
      "-o output: output filename\n"
#if defined(DEBUG)
      "-d+      : show debug information (-d stdout, -D stderr)\n"
#endif
      "-v+      : be verbose (-v stdout, -V stderr)\n"
      "-v       : report current exposure and image\n"
      "-vv      : also report ...\n"
      "-vvv     : also report ...\n"
      "-z       : suppress informative messages\n"
      "--       : end option section\n\n"
   , title, getprogname() );

   return status;
}
Generated on Thu Jan 30 10:06:38 2003 for mymain by doxygen 1.3-rc2


Page Index

mymain Related Pages

Here is a list of all related documentation pages:
  • Bug List
Generated on Thu Jan 30 10:06:40 2003 for mymain by doxygen 1.3-rc2


Bug List

Member getopt (int argc, char *argv[], char *optstring)
  • Long options are not supported.
  • The GNU double-colon extension is not supported.
  • The environment variable POSIXLY_CORRECT is not supported.
  • The + syntax is not supported.
  • The automatic permutation of arguments is not supported.
  • This implementation of getopt() returns EOF if an error is encountered, instead of -1 as the latest standard requires.
Generated on Thu Jan 30 10:06:38 2003 for mymain by doxygen 1.3-rc2


tools.h Source File

tools.h

00001 /*
00002  * tools.h - error handling and filename tools.
00003  *
00004  * code inspired by the books:
00005  *
00006  * The Unix Programming Environment
00007  * Brian W. Kernighan and Rob Pike.
00008  * Prentice Hall, Inc., 1984.
00009  * ISBN 0-13-937681-X (paperback), 0-13-937699-2 (hardback).
00010  *
00011  * The Practice of Programming.
00012  * Brian W. Kernighan and Rob Pike.
00013  * Addison-Wesley, Reading, Massachusetts, 1999.
00014  * ISBN 0-201-61586-X.
00015  *
00016  * $Revision: $
00017  * $Date: $
00018  * $Source: $
00019  * %Author: Martin J. Moene %
00020  *
00021  * Compiler        : Borland-C++ 5.5.1, GCC 3.2
00022  * Operating system: 32-bit Windows, Unix
00023  * Hardware system : PC, other
00024  *
00025  * This software is released into the public domain.
00026  * You are free to use it in any way you like.
00027  *
00028  * This software is provided "as is" with no expressed
00029  * or implied warranty.  I accept no liability for any
00030  * damage or loss of business that this software may cause.
00031  */
00032
00039 #ifndef __TOOLS_H
00040 #define __TOOLS_H
00041
00042 #if defined( __BORLANDC__ )
00043 #   include   <stdio>           // for FILE
00044 #   include  <string>           // for class string
00045 #elif defined( __MINGW32__ ) || defined( __GNUC__ )
00046 #   include  <cstdio>           // for FILE
00047 #   include  <string>           // for class string
00048 #else
00049 #error Unhandled compiler-specific include file selection.
00050 #endif
00051
00052 using namespace std;
00053
00058 enum            // program return codes
00059 {
00060    E_OK,
00061    E_OPT,
00062    E_PS,
00063    E_INT,
00064    E_ITL
00065 };
00066
00071 enum            // message levels
00072 {
00073    MSG_L0,
00074    MSG_L1,
00075    MSG_L2
00076 };
00077
00082 enum            // debug levels
00083 {
00084    DBG_L0,
00085    DBG_L1,
00086    DBG_L2
00087 };
00088
00089 /*
00090  * prototypes:
00091  */
00092
00093 const char *getprogname();
00094 void        setprogname( const char *name );
00095
00096 int         getmsglevel(            );
00097 void        setmsglevel( int  level );
00098 FILE *      getmsgfile (            );
00099 void        setmsgfile ( FILE *file );
00100
00101 int         getdbglevel(            );
00102 void        setdbglevel( int  level );
00103 FILE *      getdbgfile (            );
00104 void        setdbgfile ( FILE *file );
00105
00106 const char *dirname    ( const char *pathname );
00107 const char *basename   ( const char *pathname );
00108 const char *extname    ( const char *pathname );
00109
00110 int         exist      ( const char *filename );
00111
00112 int         error      ( int status, const char *format ...);
00113 int         message    ( int level , const char *format ...);
00114 int         debug      ( int level , const char *format ...);
00115
00116 string      prompt     ( const char *ps );
00117 int         pick       ( int isInteractive, const char *arg, const char *set = "yY" );
00118 int         ttyin      ( );
00119
00120 #endif  // __TOOLS_H
00121
00122 //\@}
00123
00124 /*
00125  * end of file
00126  */
00127
Generated on Thu Jan 30 10:06:38 2003 for mymain by doxygen 1.3-rc2


version.h Source File

version.h

00001 /*
00002  * version.h - version string for {program}.
00003  *
00004  * {project_name}.
00005  *
00006  * Copyright 2003 (C), {copyright_holder}. All rights reserved.
00007  * {project_name} is free software.  See the file Copying for copying permission.
00008  *
00009  * Source  : version.h
00010  * Author  : Martin J. Moene
00011  *
00012  * Compiler        : Borland-C++ 5.5.1, gcc
00013  * Operating system: 32-bit Windows, Unix
00014  * Hardware system : PC, other
00015  */
00016
00017 #ifndef __VERSION_H
00018 #define __VERSION_H
00019
00020 #undef  VERSION_STRING
00021 #undef  VERSION_FILE
00022
00023 #define PRODUCT_NAME   "{product_name}"
00024 #define VERSION_PRODUCT 0,1,0,0
00025
00026 #define VERSION_STRING "0.1.0 (dd mon yyyy)"
00027 #define VERSION_FILE    0,1,0,0
00028
00029 #endif
00030
00031 /*
00032  * end of file
00033  */
00034
Generated on Thu Jan 30 10:06:38 2003 for mymain by doxygen 1.3-rc2


XGetopt.h Source File

XGetopt.h

00001 // XGetopt.h
00002 //
00003 // Author:  Hans Dietrich
00004 //          hdietrich2@hotmail.com
00005 //
00006 // Adapted: Martin J. Moene <moene@biophys.LeidenUniv.nl>
00007 //          doxygen documentation, MinGW32/GCC (2003-01-20)
00008 //
00009 // This software is released into the public domain.
00010 // You are free to use it in any way you like.
00011 //
00012 // This software is provided "as is" with no expressed
00013 // or implied warranty.  I accept no liability for any
00014 // damage or loss of business that this software may cause.
00015 //
00017
00018 #ifndef XGETOPT_H
00019 #define XGETOPT_H
00020
00036 extern int optind;
00037
00044 extern int opterr;
00045
00054 extern char *optarg;
00055
00056 int getopt(int argc, char *argv[], char *optstring);
00057
00058 // @}
00059
00060 #endif //XGETOPT_H
Generated on Thu Jan 30 10:06:38 2003 for mymain by doxygen 1.3-rc2