2 * argv_parse.c --- utility function for parsing a string into a
5 * This file defines a function argv_parse() which parsing a
6 * passed-in string, handling double quotes and backslashes, and
7 * creates an allocated argv vector which can be freed using the
8 * argv_free() function.
10 * See argv_parse.h for the formal definition of the functions.
12 * Copyright 1999 by Theodore Ts'o.
14 * Permission to use, copy, modify, and distribute this software for
15 * any purpose with or without fee is hereby granted, provided that
16 * the above copyright notice and this permission notice appear in all
17 * copies. THE SOFTWARE IS PROVIDED "AS IS" AND THEODORE TS'O (THE
18 * AUTHOR) DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
19 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
21 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
22 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
23 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
24 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. (Isn't
25 * it sick that the U.S. culture of lawsuit-happy lawyers requires
26 * this kind of disclaimer?)
28 * Version 1.1, modified 2/27/1999
37 #include "argv_parse.h"
39 #define STATE_WHITESPACE 1
41 #define STATE_QUOTED 3
44 * Returns 0 on success, -1 on failure.
46 int argv_parse(char *in_buf, int *ret_argc, char ***ret_argv)
48 int argc = 0, max_argc = 0;
49 char **argv, **new_argv, *buf, ch;
50 char *cp = 0, *outcp = 0;
51 int state = STATE_WHITESPACE;
53 buf = malloc(strlen(in_buf)+1);
57 max_argc = 0; argc = 0; argv = 0;
59 for (cp = in_buf; (ch = *cp); cp++) {
60 if (state == STATE_WHITESPACE) {
61 if (isspace((int) ch))
63 /* Not whitespace, so start a new token */
65 if (argc >= max_argc) {
67 new_argv = realloc(argv,
68 (max_argc+1)*sizeof(char *));
78 if (state == STATE_QUOTED) {
85 /* Must be processing characters in a word */
86 if (isspace((int) ch)) {
88 * Terminate the current word and start
89 * looking for the beginning of the next word.
92 state = STATE_WHITESPACE;
103 ch = '\\'; cp--; break;
114 if (state != STATE_WHITESPACE)
117 argv = malloc(sizeof(char *));
128 void argv_free(char **argv)
141 int main(int argc, char **argv)
147 while (!feof(stdin)) {
148 if (fgets(buf, sizeof(buf), stdin) == NULL)
150 ret = argv_parse(buf, &ac, &av);
152 printf("Argv_parse returned %d!\n", ret);
155 printf("Argv_parse returned %d arguments...\n", ac);
156 for (cpp = av; *cpp; cpp++) {
159 printf("'%s'", *cpp);