---
name: "Cgetopt"
section: "3"
platform: "linux"
package: "liblcgdm-dev"
version: "1.10.0-2+b3"
release: "Debian 10 (Buster)"
platforms: ["linux"]
url: "https://new.carta.tech/Cgetopt"
---

# Cgetopt(3)

get long options from command line argument list

## NAME

Cgetopt\_long - get long options from command line argument list

## SYNOPSIS

**#include \<Cgetopt.h\>**

**int Cgetopt (int** *argc***, char \*\****argv***, char \****optstring***)**\
 **int Cgetopt\_long (int** *argc***, char \*\****argv***, char \****optstring***, Coptions\_t \****long\_options***, int \****index***)**

## DESCRIPTION

The **Cgetopt** function incrementally parses a command line argument list *argv* and returns the next known option character. An option character is known if it has been specified in the string of accepted option characters *optstring*.

The  **Cgetopt\_long** function is similar to  **Cgetopt** but it accepts options in two forms: words and characters. The **Cgetopt\_long** function provides a superset of the functionality of  **Cgetopt**. The additional functionality is described in the section CGETOPT\_LONG.

The option string *optstring* may contain the following elements: individual characters, and characters followed by a colon to indicate an option argument is to follow. For example, an option string **x** recognizes an option **x ,** and an option string **x:** recognizes an option **x** taking an argument. It does not matter to **Cgetopt** if a following argument has leading white space.

On return from **Cgetopt**, **Coptarg** points to an option argument, if it is anticipated, and the variable **Coptind** contains the index to the next *argv* argument for a subsequent call to **Cgetopt**. The variable **Coptopt** saves the last known option character returned by **Cgetopt**.

The variables **Copterr** and **Coptind** are both initialized to 1. The **Coptind** variable may be set to another value before a set of calls to **Cgetopt** in order to skip over more or less argv entries.

In order to use **Cgetopt** to evaluate multiple sets of arguments, or to evaluate a single set of arguments multiple times, the variable **Coptreset** must be set to 1 before the second and each additional set of calls to **Cgetopt** and the variable **Coptind** must be reinitialized.

The **Cgetopt** function returns -1 when the argument list is exhausted, or a non-recognized option is encountered. The interpretation of options in the argument list may be cancelled by the option **--** (double dash) which causes **Cgetopt** to signal the end of argument processing and returns -1. When all options have been processed (i.e., up to the first non-option argument), **Cgetopt** returns -1.

**Cgetopt\_long** can be used in two ways. In the first way, every long option understood by the program has a coresponding short option, and the option structure is only used to translate from long option to short options. When used in this fashion,  **Cgetopt\_long** behaves identically to  **Cgetopt**. This is good way to add long option processing to an existing program with the minimum of rewriting.

In the second mechanism, a long option set a flag in the  **Coptions\_t** structure passed, or will store a pointer to the command line argument in the  **Coptions\_t** structure passed to it for options that take arguments. Additionally, the long option's argument may be specified as a single argument with an equal sign, e.g **myprogram --myoption=somevalue**

When a long option is processed the call to  **Cgetopt\_long** will return 0. For this reason, long option processing without shortcuts are not backwards compatible with  **Cgetopt.**

It is possible to combine these methods, providing for long options processing with short option equivalents for some options. Less frequently used options would be processed as long options only.

## USAGE OF CGETOPT\_LONG

The  **Cgetopt\_long** call requires a structure to be initialized describing the long options. The structure is:

```

Coptions_t {
    char *name;
    int has_arg;
    int *flag;
    int val;
};
```

The  *name* field should contain the option name without the leading double dash.

The  *has\_arg* field should be one of: **NO\_ARGUMENT** if no argument to the option is expected, **REQUIRED\_ARGUMENT** if an argument to the option is required or **OPTIONAL\_ARGUMENT** if an argument to the option may be presented.

If *flag* is non-NULL, then the integer pointed to by it will set to the value in the  *val* field. If the  *flag* field is NULL, then the  *val* field will be returned. Setting  *flag* to NULL and setting *val* to the corresponding short option will make this function act just like **Cgetopt**.

## DIAGNOSTICS

If the **Cgetopt** function encounters a character not found in the string *optstring* or detects a missing option argument it writes an error message to **stderr** and returns **?**. Setting **Copterr** to a zero will disable these error messages. If *optstring* has a leading **:** then a missing option argument causes a **:** to be returned in addition to suppressing any error messages.

Option arguments are allowed to begin with **-** ; this is reasonable but reduces the amount of error checking possible.

## CGETOPT\_LONG EXTENSIONS

The **Coptreset** variable was added to make it possible to call the **Cgetopt** function multiple times. This is an extension to the **-p1003.2** specification.

## EXAMPLE

```

#include <Cgetopt.h>
int bflag, ch, fd;
Coptind = 1;            /* Required */
Copterr = 1;            /* Some stderr output if you want */
bflag = 0;
while ((ch = Cgetopt(argc, argv, "bf:")) != -1)
	switch(ch) {
	case 'b':
		bflag = 1;
		break;
	case 'f':
		if ((fd = open(Coptarg, O_RDONLY, 0)) < 0) {
			(void)fprintf(stderr,
			    "myname: %s: %s\n", Coptarg, strerror(errno));
			exit(1);
		}
		break;
	case '?':
	default:
		usage();
}
argc -= Coptind;
argv += Coptind;
```

## LONG EXAMPLE

```

#include <Cgetopt.h>
int bflag, ch, fd;
int daggerset;
/* options descriptor */
Coptions_t longopts[] =
{
  {"buffy",       NO_ARGUMENT,        NULL,      'b'},
  {"floride",     REQUIRED_ARGUMENT,  NULL,      'f'},
  {"daggerset",   NO_ARGUMENT,        &daggerset,  1},
  {NULL,          0,                  NULL,        0}
};
Coptind = 1;            /* Required */
Copterr = 1;            /* Some stderr output if you want */
bflag = 0;
while ((ch = Cgetopt_long(argc, argv, "bf:", longopts, NULL)) != -1)
	switch(ch) {
	case 'b':
		bflag = 1;
		break;
	case 'f':
		if ((fd = open(Coptarg, O_RDONLY, 0)) < 0) {
			(void)fprintf(stderr,
			    "myname: %s: %s\n", Coptarg, strerror(errno));
			exit(1);
		}
		break;
	case 0:
		if(daggerset) {
			fprintf(stderr,"Buffy will put use her dagger"
				       "to apply floride to dracula's teeth");
		}
		break;
	case '?':
	default:
		usage();
}
argc -= Coptind;
argv += Coptind;
```

## HISTORY

The **Cgetopt** function appeared in BSD 4.3. The  **Cgetopt\_long** function first appeared in GNU library. This implementation was imported to NetBSD from a Kerberos distribution.

## BUGS

The **Cgetopt** function was once specified to return **EOF** instead of -1. This was changed by **-p1003.2-92** to decouple **Cgetopt** from \<stdio.h\>.

A single dash **-** may be specified as an character in *optstring*, however it should **never** have an argument associated with it. This allows **Cgetopt** to be used with programs that expect **-** as an option flag. This practice is wrong, and should not be used in any current development. It is provided for backward compatibility **only**. By default, a single dash causes **Cgetopt** to return -1. This is, we believe, compatible with System V.

It is also possible to handle digits as option letters. This allows **Cgetopt** to be used with programs that expect a number **-3** as an option. This practice is wrong, and should not be used in any current development. It is provided for backward compatibility **only**. The following code fragment works in most cases.

```

int length;
char *p;
Coptind = 1;            /* Required */
Copterr = 1;            /* Some stderr output if you want */
while ((c = Cgetopt(argc, argv, "0123456789")) != -1)
	switch (c) {
	case '0': case '1': case '2': case '3': case '4':
	case '5': case '6': case '7': case '8': case '9':
		p = argv[Coptind - 1];
		if (p[0] == '-' && p[1] == ch && !p[2])
			length = atoi(++p);
		else
			length = atoi(argv[Coptind] + 1);
		break;
	}
}
```

The  **OPTIONAL\_ARGUMENT** always eats the following argument unless the argument is included via the  **--option=argument** notation.

## AUTHOR

Copyright (c) 1988, 1991, 1993 The Regents of the University of California.  All rights reserved.\
 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\
 1\. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\
 2\. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\
 3\. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the University of California, Berkeley and its contributors.\
 4\. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\
 THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS \`\`AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
