Thread View: de.comp.sources.unix
1 messages
1 total messages
Started by Frank Kaefer
Thu, 06 Aug 1992 21:10
v01i010: Crefine - C language extension, Part02/06
Author: Frank Kaefer
Date: Thu, 06 Aug 1992 21:10
Date: Thu, 06 Aug 1992 21:10
1203 lines
45966 bytes
45966 bytes
Submitted-by: prechelt@ira.uka.de (Lutz Prechelt)
Posting-number: Volume 1, Issue 10
Archive-name: crefine/part02
#! /bin/sh
# This is a shell archive. Remove anything before this line, then unpack
# it by saving it into a file and typing "sh file". To overwrite existing
# files, type "sh file -c". You can also feed this as standard input via
# unshar, or by typing "sh <file", e.g.. If this archive is complete, you
# will see the following message at the end:
# "End of archive 2 (of 6)."
# Contents: crefine/COPYING crefine/getargs.c crefine/getargs.cr
# Wrapped by fkk@stasys on Thu Aug 6 22:49:34 1992
PATH=/bin:/usr/bin:/usr/ucb ; export PATH
if test -f 'crefine/COPYING' -a "${1}" != "-c" ; then
echo shar: Will not clobber existing file \"'crefine/COPYING'\"
else
echo shar: Extracting \"'crefine/COPYING'\" \(12488 characters\)
sed "s/^X//" >'crefine/COPYING' <<'END_OF_FILE'
X
X GNU GENERAL PUBLIC LICENSE
X Version 1, February 1989
X
X Copyright (C) 1989 Free Software Foundation, Inc.
X 675 Mass Ave, Cambridge, MA 02139, USA
X Everyone is permitted to copy and distribute verbatim copies
X of this license document, but changing it is not allowed.
X
X Preamble
X
X The license agreements of most software companies try to keep users
Xat the mercy of those companies. By contrast, our General Public
XLicense is intended to guarantee your freedom to share and change free
Xsoftware--to make sure the software is free for all its users. The
XGeneral Public License applies to the Free Software Foundation's
Xsoftware and to any other program whose authors commit to using it.
XYou can use it for your programs, too.
X
X When we speak of free software, we are referring to freedom, not
Xprice. Specifically, the General Public License is designed to make
Xsure that you have the freedom to give away or sell copies of free
Xsoftware, that you receive source code or can get it if you want it,
Xthat you can change the software or use pieces of it in new free
Xprograms; and that you know you can do these things.
X
X To protect your rights, we need to make restrictions that forbid
Xanyone to deny you these rights or to ask you to surrender the rights.
XThese restrictions translate to certain responsibilities for you if you
Xdistribute copies of the software, or if you modify it.
X
X For example, if you distribute copies of a such a program, whether
Xgratis or for a fee, you must give the recipients all the rights that
Xyou have. You must make sure that they, too, receive or can get the
Xsource code. And you must tell them their rights.
X
X We protect your rights with two steps: (1) copyright the software, and
X(2) offer you this license which gives you legal permission to copy,
Xdistribute and/or modify the software.
X
X Also, for each author's protection and ours, we want to make certain
Xthat everyone understands that there is no warranty for this free
Xsoftware. If the software is modified by someone else and passed on, we
Xwant its recipients to know that what they have is not the original, so
Xthat any problems introduced by others will not reflect on the original
Xauthors' reputations.
X
X The precise terms and conditions for copying, distribution and
Xmodification follow.
X
X GNU GENERAL PUBLIC LICENSE
X TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
X
X 0. This License Agreement applies to any program or other work which
Xcontains a notice placed by the copyright holder saying it may be
Xdistributed under the terms of this General Public License. The
X"Program", below, refers to any such program or work, and a "work based
Xon the Program" means either the Program or any work containing the
XProgram or a portion of it, either verbatim or with modifications. Each
Xlicensee is addressed as "you".
X
X 1. You may copy and distribute verbatim copies of the Program's source
Xcode as you receive it, in any medium, provided that you conspicuously and
Xappropriately publish on each copy an appropriate copyright notice and
Xdisclaimer of warranty; keep intact all the notices that refer to this
XGeneral Public License and to the absence of any warranty; and give any
Xother recipients of the Program a copy of this General Public License
Xalong with the Program. You may charge a fee for the physical act of
Xtransferring a copy.
X
X 2. You may modify your copy or copies of the Program or any portion of
Xit, and copy and distribute such modifications under the terms of Paragraph
X1 above, provided that you also do the following:
X
X a) cause the modified files to carry prominent notices stating that
X you changed the files and the date of any change; and
X
X b) cause the whole of any work that you distribute or publish, that
X in whole or in part contains the Program or any part thereof, either
X with or without modifications, to be licensed at no charge to all
X third parties under the terms of this General Public License (except
X that you may choose to grant warranty protection to some or all
X third parties, at your option).
X
X c) If the modified program normally reads commands interactively when
X run, you must cause it, when started running for such interactive use
X in the simplest and most usual way, to print or display an
X announcement including an appropriate copyright notice and a notice
X that there is no warranty (or else, saying that you provide a
X warranty) and that users may redistribute the program under these
X conditions, and telling the user how to view a copy of this General
X Public License.
X
X d) You may charge a fee for the physical act of transferring a
X copy, and you may at your option offer warranty protection in
X exchange for a fee.
X
XMere aggregation of another independent work with the Program (or its
Xderivative) on a volume of a storage or distribution medium does not bring
Xthe other work under the scope of these terms.
X
X 3. You may copy and distribute the Program (or a portion or derivative of
Xit, under Paragraph 2) in object code or executable form under the terms of
XParagraphs 1 and 2 above provided that you also do one of the following:
X
X a) accompany it with the complete corresponding machine-readable
X source code, which must be distributed under the terms of
X Paragraphs 1 and 2 above; or,
X
X b) accompany it with a written offer, valid for at least three
X years, to give any third party free (except for a nominal charge
X for the cost of distribution) a complete machine-readable copy of the
X corresponding source code, to be distributed under the terms of
X Paragraphs 1 and 2 above; or,
X
X c) accompany it with the information you received as to where the
X corresponding source code may be obtained. (This alternative is
X allowed only for noncommercial distribution and only if you
X received the program in object code or executable form alone.)
X
XSource code for a work means the preferred form of the work for making
Xmodifications to it. For an executable file, complete source code means
Xall the source code for all modules it contains; but, as a special
Xexception, it need not include source code for modules which are standard
Xlibraries that accompany the operating system on which the executable
Xfile runs, or for standard header files or definitions files that
Xaccompany that operating system.
X
X 4. You may not copy, modify, sublicense, distribute or transfer the
XProgram except as expressly provided under this General Public License.
XAny attempt otherwise to copy, modify, sublicense, distribute or transfer
Xthe Program is void, and will automatically terminate your rights to use
Xthe Program under this License. However, parties who have received
Xcopies, or rights to use copies, from you under this General Public
XLicense will not have their licenses terminated so long as such parties
Xremain in full compliance.
X
X 5. By copying, distributing or modifying the Program (or any work based
Xon the Program) you indicate your acceptance of this license to do so,
Xand all its terms and conditions.
X
X 6. Each time you redistribute the Program (or any work based on the
XProgram), the recipient automatically receives a license from the original
Xlicensor to copy, distribute or modify the Program subject to these
Xterms and conditions. You may not impose any further restrictions on the
Xrecipients' exercise of the rights granted herein.
X
X 7. The Free Software Foundation may publish revised and/or new versions
Xof the General Public License from time to time. Such new versions will
Xbe similar in spirit to the present version, but may differ in detail to
Xaddress new problems or concerns.
X
XEach version is given a distinguishing version number. If the Program
Xspecifies a version number of the license which applies to it and "any
Xlater version", you have the option of following the terms and conditions
Xeither of that version or of any later version published by the Free
XSoftware Foundation. If the Program does not specify a version number of
Xthe license, you may choose any version ever published by the Free Software
XFoundation.
X
X 8. If you wish to incorporate parts of the Program into other free
Xprograms whose distribution conditions are different, write to the author
Xto ask for permission. For software which is copyrighted by the Free
XSoftware Foundation, write to the Free Software Foundation; we sometimes
Xmake exceptions for this. Our decision will be guided by the two goals
Xof preserving the free status of all derivatives of our free software and
Xof promoting the sharing and reuse of software generally.
X
X NO WARRANTY
X
X 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
XFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
XOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
XPROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
XOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
XMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
XTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
XPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
XREPAIR OR CORRECTION.
X
X 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
XWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
XREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
XINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
XOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
XTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
XYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
XPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
XPOSSIBILITY OF SUCH DAMAGES.
X
X END OF TERMS AND CONDITIONS
X
X Appendix: How to Apply These Terms to Your New Programs
X
X If you develop a new program, and you want it to be of the greatest
Xpossible use to humanity, the best way to achieve this is to make it
Xfree software which everyone can redistribute and change under these
Xterms.
X
X To do so, attach the following notices to the program. It is safest to
Xattach them to the start of each source file to most effectively convey
Xthe exclusion of warranty; and each file should have at least the
X"copyright" line and a pointer to where the full notice is found.
X
X <one line to give the program's name and a brief idea of what it does.>
X Copyright (C) 19yy <name of author>
X
X This program is free software; you can redistribute it and/or modify
X it under the terms of the GNU General Public License as published by
X the Free Software Foundation; either version 1, or (at your option)
X any later version.
X
X This program is distributed in the hope that it will be useful,
X but WITHOUT ANY WARRANTY; without even the implied warranty of
X MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
X GNU General Public License for more details.
X
X You should have received a copy of the GNU General Public License
X along with this program; if not, write to the Free Software
X Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
X
XAlso add information on how to contact you by electronic and paper mail.
X
XIf the program is interactive, make it output a short notice like this
Xwhen it starts in an interactive mode:
X
X Gnomovision version 69, Copyright (C) 19xx name of author
X Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
X This is free software, and you are welcome to redistribute it
X under certain conditions; type `show c' for details.
X
XThe hypothetical commands `show w' and `show c' should show the
Xappropriate parts of the General Public License. Of course, the
Xcommands you use may be called something other than `show w' and `show
Xc'; they could even be mouse-clicks or menu items--whatever suits your
Xprogram.
X
XYou should also get your employer (if you work as a programmer) or your
Xschool, if any, to sign a "copyright disclaimer" for the program, if
Xnecessary. Here a sample; alter the names:
X
X Yoyodyne, Inc., hereby disclaims all copyright interest in the
X program `Gnomovision' (a program to direct compilers to make passes
X at assemblers) written by James Hacker.
X
X <signature of Ty Coon>, 1 April 1989
X Ty Coon, President of Vice
X
XThat's all there is to it!
END_OF_FILE
if test 12488 -ne `wc -c <'crefine/COPYING'`; then
echo shar: \"'crefine/COPYING'\" unpacked with wrong size!
fi
# end of 'crefine/COPYING'
fi
if test -f 'crefine/getargs.c' -a "${1}" != "-c" ; then
echo shar: Will not clobber existing file \"'crefine/getargs.c'\"
else
echo shar: Extracting \"'crefine/getargs.c'\" \(14268 characters\)
sed "s/^X//" >'crefine/getargs.c' <<'END_OF_FILE'
X
X/*************************************************************************
XModule : getargs -- command line option processor
XAuthor : Lutz Prechelt, Karlsruhe
XDate : 15.11.91 Version 3
XCompiler: should be portable (ANSI-C or K&R-C)
X**************************************************************************/
X/*
X Copyright (C) 1988,91 by Lutz Prechelt, Karlsruhe
X
X This program is free software; you can redistribute it and/or modify
X it under the terms of the GNU General Public License as published by
X the Free Software Foundation; either version 1, or (at your option)
X any later version.
X This program is distributed in the hope that it will be useful,
X but WITHOUT ANY WARRANTY; without even the implied warranty of
X MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
X GNU General Public License for more details.
X You should have received a copy of the GNU General Public License
X along with this program; if not, write to the Free Software
X Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
X*/
X
X
X/************************************************************************
X*********************** g e t a r g s ***********************************
X*************************************************************************/
X#if 0
X
XVarianten:
X#define deutsch 1 waehlt deutsche Meldungen statt englische
X#define __STDC__ 1 waehlt Funktionsdefinitionen mit Parameterliste
X statt ohne
X#define ms_dos 1 erlaubt "/" als Optionszeichen zusaetzlich zu "-"
X
XDies ist ein Utility zum bequemeren Auswerten von Optionen auf der
XKommandozeile (d.h. mit argc, argv).
X
XEs wird dazu vom Benutzer eine Tabelle ("argtab") aufgestellt, in der zu
Xjeder Option der Optionsbuchstabe, ein Argumententyp
X(BOOL, CHAR, INT, STRING) und eine Variable angegeben werden,
Xin der das Resultat abgelegt werden soll.
XFerner kann man hier noch einen Kommentarstring zu jeder Option angeben.
X
XDie Funktion getargs (&argc, argv, argtab, argtabsize) bearbeitet nun den
Xargv Vektor derart, dass alle Optionen, die in argtab angegeben sind, gemaess
Xihrem Eintrag behandelt werden und aus argv entfernt (dazu wird argc und argv
Xmodifiziert, jedoch nur Pointer veraendert, keine argv-Eintraege selbst)
XEs duerfen beim Aufruf die Optionen beliebig mit den uebrigen Parametern
Xvermischt und mehrere Optionen hinter einem Optionssymbol angegeben
Xwerden.
X
XEs werden unbekannte Optionen festgestellt und angemeckert (nach stderr)
XAls Resultat wird die Anzahl angemeckerter Optionen geliefert.
X
XDie Funktion print_usage (program_name, usage_text, argtab, argtabsize)
Xgibt unter Benutzung der Kommentarstrings aus argtab eine Kurzbeschreibung zum
Xkorrekten Aufruf aller Optionen und des Gesamtprogramms nach stderr aus.
X
XBeispiel:
X#include <getargs.h>
X int a = 1, b = 'B', c;
X char *d = "";
X ARG argtab[] = { {'a', BOOLEAN, &a, "use alternate mode" },
X {'b', CHARACTER,&b, "Character for boldface" },
X {'c', INTEGER, &c, "count of pages to print" },
X {'d', STRING , (int*)&d, "File description" } };
X void main (int argc, char **argv) {
X if (getargs (&argc, argv, argtab, ARGTABSIZE (argtab)))
X print_usage (argv[0], "[options] filetoprint [options]", argtab,
X ARGTABSIZE (argtab));
X }
X
XEnthalte argtab also die Liste der Optionen fuer das Programm "fileprt", das
X(wie in print_usage angegeben) noch einen Dateinamen als weiteren Parameter
Xverlangt.
X
XDann waeren korrekte Aufrufe etwa:
X
Xfileprt -a file
Xfileprt -a+ file -bB
Xfileprt -c14 file -dMyFile
Xfileprt file -abBc14
X
XVerkehrt waere dagegen zum Beispiel:
X
Xfileprt -dMy File file weil <File> ein eigenes Argument ist
Xfileprt -p file weil es die Option p nicht gibt
Xfileprt -bx28 file weil CHAR immer nur ein Zeichen umfasst
X
XDieser letzte Aufruf haette im Beispiel ungefaehr folgenden Output nach
Xstderr zur Folge:
X
XUnknown option : -bx28
Xusage: fileprt [options] filetoprint
Xvalid options are:
X-a<+/-> use alternate mode (Wert: TRUE)
X-b<ch> Character for boldface (Wert: B)
X-c<num> count of pages to print (Wert: 0)
X-d<str> File description (Wert: "")
X
XDer genaue Grund fuer die Fehlermeldung ist, dass der Interpreter der Option
Xb den Wert x zuweist und dann nach der (nicht auffindbaren) Option 2 sucht !
X
XDie "Wert"-Angaben beim print_usage entstehen aus den Vorbelegungen der
XVariablen a, b, c, d;
X
X#endif
X
X/**************************************************************************/
X
X#include "std.h"
X#include <stdio.h>
X#include <ctype.h>
X#include "getargs.h"
X
X#if deutsch
X#define ERRMSG "Unbekannte oder falsch benutzte Option"
X#define USAGE "Aufruf"
X#define VALID_OPT_ARE "Erlaubte Optionen sind"
X#else
X#define ERRMSG "unknown or malformed option"
X#define USAGE "usage"
X#define VALID_OPT_ARE "valid options are"
X#endif
X
X#define is_option(a) (*(a) == '-' && *(a+1) != 0)
X
Xstatic int set_argument A((ARG* entry, char **optiontext, char **next_arg));
Xstatic ARG* find_argument A((int optionname, ARG *argtab, int argtablength));
Xstatic int stoi A((char **linep, int *result));
X
X/*---------------------------------------------------------
X * getargs
X *---------------------------------------------------------*/
X
Xextern int getargs (argc, argv, tabp, tabsize)
X int *argc; /* changed */
X char ***argv; /* changed */
X ARG *tabp;
X int tabsize;
X{
X /* Main routine. Evaluates all arguments in argv up to argc:
X Options (known from first letter as given by macro is_option)
X are followed by other arguments.
X -- forces end of options.
X options are searched for in tabp and are removed from argv by
X shifting the remaining arguments left.
X options are handled according to their tabp entry,
X illegal options or missing or illegal values are complained.
X Otherwise the corresponding variable is set according to the value
X given with the option.
X Only non-options are still in argv after this procedure, their
X number is given back in *argc.
X The return value is the number of errors found.
X */
X char *p, *argv0 = **argv, *nilarg = "";
X int errors = 0, error;
X ARG *argp;
X for ((*argv)++; --(*argc) > 0; (*argv)++)
X { /* handle_this_arg (Level 1) */
X if ((
X /* the argument "--" forces end of option processing */
X (*argv)[0][0] == '-' && (*argv)[0][1] == '-' && (*argv)[0][2] == 0)
X ) {
X **argv = argv0; /* restore program name */
X return (errors);
X }
X else if (!is_option (**argv)) {
X (*argv)--; (*argc)++;
X **argv = argv0; /* restore program name */
X return (errors);
X }
X else {
X char **next_arg = *argc > 1 ? (*argv)+1 : &nilarg;
X p = (**argv) + 1; /* Option -> handle it */
X while (*p) {
X error = 0;
X /* One Optionsign can have multiple Options following */
X if (argp = find_argument ((int)*p, tabp, tabsize)) /* if exists */
X { /* read_option_value (Level 2) */
X error = !set_argument (argp, &p, next_arg);
X }
X if (!argp || error) { /* if not exists or invalid value */
X fprintf (stderr, "%s : %s\n", ERRMSG, **argv); /* then #$% */
X errors++;
X break;
X }
X if (*next_arg == 0) { /* Next argv element already used up */
X (*argv)++;
X (*argc)--;
X }
X }
X }
X }
X (*argv)--;
X **argv = argv0; /* restore program name */
X return (errors);
X}
X
X/*---------------------------------------------------------
X * set_argument
X *---------------------------------------------------------*/
X
Xstatic int set_argument (argp, linep, next_arg)
X ARG *argp;
X char **linep, **next_arg;
X{
X /* Gets the argument for the current option into the corresponding
X variable as given in argtab.
X linep is incremented as much as necessary (as much as data is
X used for the value).
X If no value can be found in linep, next_arg is searched for it,
X and, if found, set to 0.
X Returns 1 (or 0 on errors, i.e. illegal or missing values)
X */
X#define p (argp->variable)
X char *old_linep, *old_next_arg = *next_arg;
X ++(*linep); /* skip Optionname */
X old_linep = *linep;
X switch (argp->type) {
X case INTEGER:
X { /* get_integer (Level 1) */
X stoi (linep, p);
X if (old_linep == *linep) { /* no integer found in linep */
X stoi (next_arg, p);
X if (old_next_arg != *next_arg)
X *next_arg = 0;
X }
X return (old_linep != *linep || *next_arg == 0);
X }
X case BOOLEAN:
X { /* get_bool (Level 1) */
X if ((
X **linep == '-' || **linep == '+')
X ) { /* + or - given right behind */
X *p = (**linep == '+');
X ++(*linep);
X }
X else if ((
X **linep != 0)
X ) /* no value given */
X *p = 1; /* assume true */
X else if ((
X (**next_arg == '-' || **next_arg == '+') &&
X (*next_arg)[1] == 0)
X ) {
X *p = **next_arg == '+';
X *next_arg = 0;
X }
X else /* else assume TRUE */
X *p = 1;
X return (1);
X }
X case CHARACTER:
X { /* get_char (Level 1) */
X *p = (int)**linep;
X if (*p != 0) {
X ++(*linep); /* go on one char */
X return (1);
X }
X /* we must get character from next_arg, if possible */
X if ((
X (*next_arg)[0] != 0 && (*next_arg)[1] == 0)
X ) {
X *p = **next_arg;
X *next_arg = 0;
X return (1);
X }
X else
X return (0);
X }
X case STRING:
X { /* get_string (Level 1) */
X if (**linep != 0) {
X *(char **)p = *linep;
X *linep = ""; /* take all the rest */
X return (1);
X }
X /* we must get string from next_arg */
X *(char **)p = *next_arg;
X *next_arg = 0;
X return (1);
X
X#undef p
X }
X }
X return (0); /* just to keep certain compilers quiet */
X}
X
X/*---------------------------------------------------------
X * find_argument
X *---------------------------------------------------------*/
X
Xstatic ARG* find_argument (optionname, tabp, tabsize)
X int optionname;
X ARG *tabp;
X int tabsize;
X{
X for (; --tabsize >= 0; tabp++)
X if (tabp->arg == optionname)
X return (tabp);
X return (0); /* not found */
X}
X
X/*---------------------------------------------------------
X * print_usage
X *---------------------------------------------------------*/
X
Xextern void print_usage (progname, usage, tabp, tabsize)
X char *progname, *usage;
X ARG *tabp;
X int tabsize;
X{
X /* Druckt die Optionsbeschreibungen laut tabp incl. momentaner Werte der
X zugeh. Variablen sowie zuvor eine "usage:" Zeile mit den Texten
X progname und usage.
X */
X char *p;
X int i;
X fprintf (stderr, "\n%s: %s %s\n%s:\n", USAGE, progname,
X usage, VALID_OPT_ARE);
X for (i = 0; i < tabsize; i++, tabp++) {
X fprintf (stderr, "-%c", tabp->arg);
X p = tabp->errmsg;
X switch (tabp->type) {
X case INTEGER:
X fprintf (stderr, "<num> %-45s (%d)\n",
X p, *(tabp->variable));
X break;
X case BOOLEAN:
X fprintf (stderr, "<+/-> %-45s (%s)\n",
X p, *(tabp->variable) ? "TRUE" : "FALSE");
X break;
X case CHARACTER:
X fprintf (stderr, "<ch> %-45s (%c)\n",
X p, (char)*(tabp->variable));
X break;
X case STRING:
X fprintf (stderr, "<str> %-45s (\"%s\")\n",
X p, *(char **)tabp->variable);
X break;
X }
X }
X}
X
X
X/********************* Hilfsfunktionen ************************************/
X
X
X/*---------------------------------------------------------
X * stoi
X *---------------------------------------------------------*/
X
Xstatic int stoi (instr, result)
X char **instr;
X int *result;
X{
X /* tries to read a decimal, octal or hexadecimal number from *instr
X and advances *instr accordingly.
X returns whether a number could successfully be read.
X the number read is returned in *result.
X */
X int error = 1;
X int num = 0;
X int sign = 0; /* Betrag und neg. Vorzeichen des Resultats */
X char *str = *instr;
X while (isspace (*str))
X str++;
X if (*str == '-') {
X sign = -1;
X str++;
X }
X if (*str == '0')
X { /* read_octal_or_hex (Level 1) */
X ++str;
X error = 0;
X if (toupper (*str) == 'X') {
X str++;
X while(isxdigit(*str)) {
X num *= 16;
X num += isdigit (*str) ? *str - '0'
X : toupper (*str) - 'A'+ 10;
X str++;
X }
X }
X else {
X while ('0' <= *str && *str <= '7') {
X num *= 8;
X num += *str++ - '0';
X }
X }
X }
X else
X { /* read_decimal (Level 1) */
X while (isdigit (*str)) {
X error = 0;
X num *= 10;
X num += *str++ - '0';
X
X }
X }
X if (error)
X return (error);
X *instr = str;
X *result = sign ? -num : num;
X return (0);
X}
X
X/************* Hauptprogramm zum Testen **********************************/
X
X#if 0
X
X int a = 0, b = 'b', c = 3;
X char *d = "";
X ARG argtab[] = { {'a', BOOLEAN, &a, "Option a" },
X {'b', CHARACTER, &b, "Option b" },
X {'c', INTEGER, &c, "Option c" },
X {'d', STRING, (int*)&d, "Option d" } };
X
Xvoid main (int argc, char **argv)
X{
X int i, n;
X printf ("Argumentpointer argv[i]: ");
X for (i = 0; i < argc; i++)
X printf ("%d ", (int)argv[i]);
X printf ("\n");
X n = getargs (&argc, argv, argtab, ARGTABSIZE (argtab));
X if (n)
X print_usage (argv [0], "rabarber", argtab, ARGTABSIZE (argtab));
X printf ("\n RESULTATE (%d): a = %d, b = '%c', c = %d, d = \"%s\"\n",
X n, a, (char)b, c, d);
X printf ("ARGV: ");
X for (i = 0; i < argc; i++)
X printf ("<%s> ", argv[i]);
X}
X
X#endif
X
END_OF_FILE
if test 14268 -ne `wc -c <'crefine/getargs.c'`; then
echo shar: \"'crefine/getargs.c'\" unpacked with wrong size!
fi
# end of 'crefine/getargs.c'
fi
if test -f 'crefine/getargs.cr' -a "${1}" != "-c" ; then
echo shar: Will not clobber existing file \"'crefine/getargs.cr'\"
else
echo shar: Extracting \"'crefine/getargs.cr'\" \(14031 characters\)
sed "s/^X//" >'crefine/getargs.cr' <<'END_OF_FILE'
X/*************************************************************************
XModule : getargs -- command line option processor
XAuthor : Lutz Prechelt, Karlsruhe
XDate : 15.11.91 Version 3
XCompiler: should be portable (ANSI-C or K&R-C)
X**************************************************************************/
X/*
X Copyright (C) 1988,91 by Lutz Prechelt, Karlsruhe
X
X This program is free software; you can redistribute it and/or modify
X it under the terms of the GNU General Public License as published by
X the Free Software Foundation; either version 1, or (at your option)
X any later version.
X This program is distributed in the hope that it will be useful,
X but WITHOUT ANY WARRANTY; without even the implied warranty of
X MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
X GNU General Public License for more details.
X You should have received a copy of the GNU General Public License
X along with this program; if not, write to the Free Software
X Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
X*/
X
X
X/************************************************************************
X*********************** g e t a r g s ***********************************
X*************************************************************************/
X#if 0
X
XVarianten:
X#define deutsch 1 waehlt deutsche Meldungen statt englische
X#define __STDC__ 1 waehlt Funktionsdefinitionen mit Parameterliste
X statt ohne
X#define ms_dos 1 erlaubt "/" als Optionszeichen zusaetzlich zu "-"
X
XDies ist ein Utility zum bequemeren Auswerten von Optionen auf der
XKommandozeile (d.h. mit argc, argv).
X
XEs wird dazu vom Benutzer eine Tabelle ("argtab") aufgestellt, in der zu
Xjeder Option der Optionsbuchstabe, ein Argumententyp
X(BOOL, CHAR, INT, STRING) und eine Variable angegeben werden,
Xin der das Resultat abgelegt werden soll.
XFerner kann man hier noch einen Kommentarstring zu jeder Option angeben.
X
XDie Funktion getargs (&argc, argv, argtab, argtabsize) bearbeitet nun den
Xargv Vektor derart, dass alle Optionen, die in argtab angegeben sind, gemaess
Xihrem Eintrag behandelt werden und aus argv entfernt (dazu wird argc und argv
Xmodifiziert, jedoch nur Pointer veraendert, keine argv-Eintraege selbst)
XEs duerfen beim Aufruf die Optionen beliebig mit den uebrigen Parametern
Xvermischt und mehrere Optionen hinter einem Optionssymbol angegeben
Xwerden.
X
XEs werden unbekannte Optionen festgestellt und angemeckert (nach stderr)
XAls Resultat wird die Anzahl angemeckerter Optionen geliefert.
X
XDie Funktion print_usage (program_name, usage_text, argtab, argtabsize)
Xgibt unter Benutzung der Kommentarstrings aus argtab eine Kurzbeschreibung zum
Xkorrekten Aufruf aller Optionen und des Gesamtprogramms nach stderr aus.
X
XBeispiel:
X #include <getargs.h>
X int a = 1, b = 'B', c;
X char *d = "";
X ARG argtab[] = { {'a', BOOLEAN, &a, "use alternate mode" },
X {'b', CHARACTER,&b, "Character for boldface" },
X {'c', INTEGER, &c, "count of pages to print" },
X {'d', STRING , (int*)&d, "File description" } };
X void main (int argc, char **argv) {
X if (getargs (&argc, argv, argtab, ARGTABSIZE (argtab)))
X print_usage (argv[0], "[options] filetoprint [options]", argtab,
X ARGTABSIZE (argtab));
X }
X
XEnthalte argtab also die Liste der Optionen fuer das Programm "fileprt", das
X(wie in print_usage angegeben) noch einen Dateinamen als weiteren Parameter
Xverlangt.
X
XDann waeren korrekte Aufrufe etwa:
X
Xfileprt -a file
Xfileprt -a+ file -bB
Xfileprt -c14 file -dMyFile
Xfileprt file -abBc14
X
XVerkehrt waere dagegen zum Beispiel:
X
Xfileprt -dMy File file weil <File> ein eigenes Argument ist
Xfileprt -p file weil es die Option p nicht gibt
Xfileprt -bx28 file weil CHAR immer nur ein Zeichen umfasst
X
XDieser letzte Aufruf haette im Beispiel ungefaehr folgenden Output nach
Xstderr zur Folge:
X
XUnknown option : -bx28
Xusage: fileprt [options] filetoprint
Xvalid options are:
X-a<+/-> use alternate mode (Wert: TRUE)
X-b<ch> Character for boldface (Wert: B)
X-c<num> count of pages to print (Wert: 0)
X-d<str> File description (Wert: "")
X
XDer genaue Grund fuer die Fehlermeldung ist, dass der Interpreter der Option
Xb den Wert x zuweist und dann nach der (nicht auffindbaren) Option 2 sucht !
X
XDie "Wert"-Angaben beim print_usage entstehen aus den Vorbelegungen der
XVariablen a, b, c, d;
X
X#endif
X
X/**************************************************************************/
X
X#include "std.h"
X#include <stdio.h>
X#include <ctype.h>
X#include "getargs.h"
X
X#if deutsch
X#define ERRMSG "Unbekannte oder falsch benutzte Option"
X#define USAGE "Aufruf"
X#define VALID_OPT_ARE "Erlaubte Optionen sind"
X#else
X#define ERRMSG "unknown or malformed option"
X#define USAGE "usage"
X#define VALID_OPT_ARE "valid options are"
X#endif
X
X#define is_option(a) (*(a) == '-' && *(a+1) != 0)
X
Xstatic int set_argument A((ARG* entry, char **optiontext, char **next_arg));
Xstatic ARG* find_argument A((int optionname, ARG *argtab, int argtablength));
Xstatic int stoi A((char **linep, int *result));
X
X/*---------------------------------------------------------
X * getargs
X *---------------------------------------------------------*/
X
Xextern int getargs (argc, argv, tabp, tabsize)
X int *argc; /* changed */
X char ***argv; /* changed */
X ARG *tabp;
X int tabsize;
X{
X /* Main routine. Evaluates all arguments in argv up to argc:
X Options (known from first letter as given by macro is_option)
X are followed by other arguments.
X -- forces end of options.
X options are searched for in tabp and are removed from argv by
X shifting the remaining arguments left.
X options are handled according to their tabp entry,
X illegal options or missing or illegal values are complained.
X Otherwise the corresponding variable is set according to the value
X given with the option.
X Only non-options are still in argv after this procedure, their
X number is given back in *argc.
X The return value is the number of errors found.
X */
X char *p, *argv0 = **argv, *nilarg = "";
X int errors = 0, error;
X ARG *argp;
X for ((*argv)++; --(*argc) > 0; (*argv)++)
X `handle this arg;
X (*argv)--;
X **argv = argv0; /* restore program name */
X return (errors);
X
X`handle this arg:
X if (`is end of options) {
X **argv = argv0; /* restore program name */
X return (errors);
X }
X else if (!is_option (**argv)) {
X (*argv)--; (*argc)++;
X **argv = argv0; /* restore program name */
X return (errors);
X }
X else {
X char **next_arg = *argc > 1 ? (*argv)+1 : &nilarg;
X p = (**argv) + 1; /* Option -> handle it */
X while (*p) {
X error = 0;
X /* One Optionsign can have multiple Options following */
X if (argp = find_argument ((int)*p, tabp, tabsize)) /* if exists */
X `read option value;
X if (!argp || error) { /* if not exists or invalid value */
X fprintf (stderr, "%s : %s\n", ERRMSG, **argv); /* then #$% */
X errors++;
X break;
X }
X if (*next_arg == 0) { /* Next argv element already used up */
X (*argv)++;
X (*argc)--;
X }
X }
X }
X
X`is end of options:
X /* the argument "--" forces end of option processing */
X (*argv)[0][0] == '-' && (*argv)[0][1] == '-' && (*argv)[0][2] == 0
X
X`read option value:
X error = !set_argument (argp, &p, next_arg);
X
X}
X
X/*---------------------------------------------------------
X * set_argument
X *---------------------------------------------------------*/
X
Xstatic int set_argument (argp, linep, next_arg)
X ARG *argp;
X char **linep, **next_arg;
X{
X /* Gets the argument for the current option into the corresponding
X variable as given in argtab.
X linep is incremented as much as necessary (as much as data is
X used for the value).
X If no value can be found in linep, next_arg is searched for it,
X and, if found, set to 0.
X Returns 1 (or 0 on errors, i.e. illegal or missing values)
X */
X#define p (argp->variable)
X char *old_linep, *old_next_arg = *next_arg;
X ++(*linep); /* skip Optionname */
X old_linep = *linep;
X switch (argp->type) {
X case INTEGER: `get integer;
X case BOOLEAN: `get bool;
X case CHARACTER: `get char;
X case STRING: `get string;
X }
X return (0); /* just to keep certain compilers quiet */
X
X`get integer:
X stoi (linep, p);
X if (old_linep == *linep) { /* no integer found in linep */
X stoi (next_arg, p);
X if (old_next_arg != *next_arg)
X *next_arg = 0;
X }
X return (old_linep != *linep || *next_arg == 0);
X
X`get bool:
X if (`plus or minus follows) { /* + or - given right behind */
X *p = (**linep == '+');
X ++(*linep);
X }
X else if (`other things follow) /* no value given */
X *p = 1; /* assume true */
X else if (`next arg is plus or minus) {
X *p = **next_arg == '+';
X *next_arg = 0;
X }
X else /* else assume TRUE */
X *p = 1;
X return (1);
X
X`plus or minus follows:
X **linep == '-' || **linep == '+'
X
X`other things follow:
X **linep != 0
X
X`next arg is plus or minus:
X (**next_arg == '-' || **next_arg == '+') &&
X (*next_arg)[1] == 0
X
X`get char:
X *p = (int)**linep;
X if (*p != 0) {
X ++(*linep); /* go on one char */
X return (1);
X }
X /* we must get character from next_arg, if possible */
X if (`next_arg is a character) {
X *p = **next_arg;
X *next_arg = 0;
X return (1);
X }
X else
X return (0);
X
X`next_arg is a character:
X (*next_arg)[0] != 0 && (*next_arg)[1] == 0
X
X`get string:
X if (**linep != 0) {
X *(char **)p = *linep;
X *linep = ""; /* take all the rest */
X return (1);
X }
X /* we must get string from next_arg */
X *(char **)p = *next_arg;
X *next_arg = 0;
X return (1);
X
X#undef p
X}
X
X/*---------------------------------------------------------
X * find_argument
X *---------------------------------------------------------*/
X
Xstatic ARG* find_argument (optionname, tabp, tabsize)
X int optionname;
X ARG *tabp;
X int tabsize;
X{
X for (; --tabsize >= 0; tabp++)
X if (tabp->arg == optionname)
X return (tabp);
X return (0); /* not found */
X}
X
X/*---------------------------------------------------------
X * print_usage
X *---------------------------------------------------------*/
X
Xextern void print_usage (progname, usage, tabp, tabsize)
X char *progname, *usage;
X ARG *tabp;
X int tabsize;
X{
X /* Druckt die Optionsbeschreibungen laut tabp incl. momentaner Werte der
X zugeh. Variablen sowie zuvor eine "usage:" Zeile mit den Texten
X progname und usage.
X */
X char *p;
X int i;
X fprintf (stderr, "\n%s: %s %s\n%s:\n", USAGE, progname,
X usage, VALID_OPT_ARE);
X for (i = 0; i < tabsize; i++, tabp++) {
X fprintf (stderr, "-%c", tabp->arg);
X p = tabp->errmsg;
X switch (tabp->type) {
X case INTEGER:
X fprintf (stderr, "<num> %-45s (%d)\n",
X p, *(tabp->variable));
X break;
X case BOOLEAN:
X fprintf (stderr, "<+/-> %-45s (%s)\n",
X p, *(tabp->variable) ? "TRUE" : "FALSE");
X break;
X case CHARACTER:
X fprintf (stderr, "<ch> %-45s (%c)\n",
X p, (char)*(tabp->variable));
X break;
X case STRING:
X fprintf (stderr, "<str> %-45s (\"%s\")\n",
X p, *(char **)tabp->variable);
X break;
X }
X }
X}
X
X
X/********************* Hilfsfunktionen ************************************/
X
X
X/*---------------------------------------------------------
X * stoi
X *---------------------------------------------------------*/
X
Xstatic int stoi (instr, result)
X char **instr;
X int *result;
X{
X /* tries to read a decimal, octal or hexadecimal number from *instr
X and advances *instr accordingly.
X returns whether a number could successfully be read.
X the number read is returned in *result.
X */
X int error = 1;
X int num = 0;
X int sign = 0; /* Betrag und neg. Vorzeichen des Resultats */
X char *str = *instr;
X while (isspace (*str))
X str++;
X if (*str == '-') {
X sign = -1;
X str++;
X }
X if (*str == '0')
X `read octal or hex;
X else
X `read decimal;
X if (error)
X return (error);
X *instr = str;
X *result = sign ? -num : num;
X return (0);
X
X`read octal or hex:
X ++str;
X error = 0;
X if (toupper (*str) == 'X') {
X str++;
X while(isxdigit(*str)) {
X num *= 16;
X num += isdigit (*str) ? *str - '0'
X : toupper (*str) - 'A'+ 10;
X str++;
X }
X }
X else {
X while ('0' <= *str && *str <= '7') {
X num *= 8;
X num += *str++ - '0';
X }
X }
X
X`read decimal:
X while (isdigit (*str)) {
X error = 0;
X num *= 10;
X num += *str++ - '0';
X
X }
X
X}
X
X/************* Hauptprogramm zum Testen **********************************/
X
X#if 0
X
X int a = 0, b = 'b', c = 3;
X char *d = "";
X ARG argtab[] = { {'a', BOOLEAN, &a, "Option a" },
X {'b', CHARACTER, &b, "Option b" },
X {'c', INTEGER, &c, "Option c" },
X {'d', STRING, (int*)&d, "Option d" } };
X
Xvoid main (int argc, char **argv)
X{
X int i, n;
X printf ("Argumentpointer argv[i]: ");
X for (i = 0; i < argc; i++)
X printf ("%d ", (int)argv[i]);
X printf ("\n");
X n = getargs (&argc, argv, argtab, ARGTABSIZE (argtab));
X if (n)
X print_usage (argv [0], "rabarber", argtab, ARGTABSIZE (argtab));
X printf ("\n RESULTATE (%d): a = %d, b = '%c', c = %d, d = \"%s\"\n",
X n, a, (char)b, c, d);
X printf ("ARGV: ");
X for (i = 0; i < argc; i++)
X printf ("<%s> ", argv[i]);
X}
X
X#endif
X
END_OF_FILE
if test 14031 -ne `wc -c <'crefine/getargs.cr'`; then
echo shar: \"'crefine/getargs.cr'\" unpacked with wrong size!
fi
# end of 'crefine/getargs.cr'
fi
echo shar: End of archive 2 \(of 6\).
cp /dev/null ark2isdone
MISSING=""
for I in 1 2 3 4 5 6 ; do
if test ! -f ark${I}isdone ; then
MISSING="${MISSING} ${I}"
fi
done
if test "${MISSING}" = "" ; then
echo You have unpacked all 6 archives.
rm -f ark[1-9]isdone
else
echo You still need to unpack the following archives:
echo " " ${MISSING}
fi
## End of shell archive.
exit 0
--
Frank Kaefer # fkk@stasys.sta.sub.org # Starnberg, Germany
Thread Navigation
This is a paginated view of messages in the thread with full content displayed inline.
Messages are displayed in chronological order, with the original post highlighted in green.
Use pagination controls to navigate through all messages in large threads.
Back to All Threads