getsubopt(3)

getsubopt3

Get sub options from an argument

Usage

#include <stdlib.h>

extern char *suboptarg;

int

getsubopt(char **optionp, char * const *tokens, char **valuep);

Library

Standard C Library (libc, -lc)

Overview

The getsubopt() function parses a string containing tokens delimited by one or more tab, space or comma (‘,’) characters. It is intended for use in parsing groups of option arguments provided as part of a utility command line.

The argument optionp is a pointer to a pointer to the string. The argument tokens is a pointer to a NULL-terminated array of pointers to strings.

The getsubopt() function returns the zero-based offset of the pointer in the tokens array referencing a string which matches the first token in the string, or, -1 if the string contains no tokens or tokens does not contain a matching string.

If the token is of the form ``name=value'', the location referenced by valuep will be set to point to the start of the ``value'' portion of the token.

On return from getsubopt(), optionp will be set to point to the start of the next token in the string, or the null at the end of the string if no more tokens are present. The external variable suboptarg will be set to point to the start of the current token, or NULL if no tokens were present. The argument valuep will be set to point to the ``value'' portion of the token, or NULL if no ``value'' portion was present.

Examples

char *tokens[] = {
	#define	ONE	0
		"one",
	#define	TWO	1
		"two",
	NULL
};
...
extern char *optarg, *suboptarg;
char *options, *value;
while ((ch = getopt(argc, argv, "ab:")) != -1) {
	switch(ch) {
	case 'a':
		/* process ``a'' option */
		break;
	case 'b':
		options = optarg;
		while (*options) {
			switch(getsubopt(&options, tokens, &value)) {
			case ONE:
				/* process ``one'' sub option */
				break;
			case TWO:
				/* process ``two'' sub option */
				if (!value)
					error("no value for two");
				i = atoi(value);
				break;
			case -1:
				if (suboptarg)
					error("illegal sub option %s",
					  suboptarg);
				else
					error("missing sub option");
				break;
			}
		}
		break;
	}
}

Releases

87 releases since FreeBSD 2.0.5-RELEASE; the text changed 41 times.

  1. 2.0.5–2.1.7.1
  2. 2.2.2–3.4
  3. 3.5–3.5.1
  4. 4.0
  5. 4.1–4.2
  6. 4.3–4.4
  7. 4.5–4.11
  8. 5.0–5.2.1
  9. 5.3–6.3
  10. 6.4
  11. 7.0
  12. 7.1
  13. 7.2
  14. 7.3
  15. 7.4
  16. 8.0
  17. 8.1
  18. 8.2
  19. 8.3
  20. 8.4
  21. 9.0
  22. 9.1
  23. 9.2
  24. 9.3
  25. 10.0
  26. 10.1
  27. 10.2
  28. 10.3
  29. 10.4
  30. 11.0
  31. 11.1
  32. 11.2
  33. 11.3
  34. 11.4
  35. 12.0
  36. 12.1
  37. 12.2
  38. 12.3
  39. 12.4
  40. 13.0–13.2
  41. 13.3–14.5
  42. 15.0–16.0

History

The getsubopt() function first appeared in 4.4BSD.

From base 16.0-CURRENT-20261027-61c70dc16a79 in FreeBSD 16.0-CURRENT (2026-10-27). Parsed by carta from the page's mdoc source.