-
Notifications
You must be signed in to change notification settings - Fork 5
/
argv.c
96 lines (77 loc) · 2.53 KB
/
argv.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
This file contains a function, build_argv(), which will take an input
string and chop it into individual words. The return value is an
argv style array (i.e. like what main() receives).
THIS CODE COPYRIGHT DOMINIC GIAMPAOLO. NO WARRANTY IS EXPRESSED
OR IMPLIED. YOU MAY USE THIS CODE AND FREELY DISTRIBUTE IT FOR
NON-COMMERCIAL USE AS LONG AS THIS NOTICE REMAINS ATTACHED.
FOR COMMERCIAL USE, CONTACT DOMINIC GIAMPAOLO ([email protected]).
Dominic Giampaolo
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "argv.h"
#define DOUBLE_QUOTE '"'
#define SINGLE_QUOTE '\''
#define BACK_SLASH '\\'
char **
build_argv(char *str, int *argc)
{
int table_size = 16, _argc;
char *ptr=str;
char **argv;
if (argc == NULL)
argc = &_argc;
*argc = 0;
argv = (char **)calloc(table_size, sizeof(char *));
if (argv == NULL)
return NULL;
while(*str) {
/* skip intervening white space */
while(*str != '\0' && (*str == ' ' || *str == '\t' || *str == '\n'))
str++;
if (*str == '\0')
break;
if (*str == DOUBLE_QUOTE) {
argv[*argc] = ++str;
while(*str && *str != DOUBLE_QUOTE) {
if (*str == BACK_SLASH)
strcpy(str, str+1); /* copy everything down */
str++;
}
} else if (*str == SINGLE_QUOTE) {
argv[*argc] = ++str;
while(*str && *str != SINGLE_QUOTE) {
if (*str == BACK_SLASH)
strcpy(str, str+1); /* copy everything down */
str++;
}
} else {
argv[*argc] = str;
while(*str && *str != ' ' && *str != '\t' && *str != '\n') {
if (*str == BACK_SLASH)
strcpy(str, str+1); /* copy everything down */
str++;
}
}
if (*str != '\0')
*str++ = '\0'; /* chop the string */
*argc = *argc + 1;
if (*argc >= table_size-1) {
char **nargv;
table_size = table_size * 2;
nargv = (char **)calloc(table_size, sizeof(char *));
if (nargv == NULL) { /* drats! failure. */
free(argv);
return NULL;
}
memcpy(nargv, argv, (*argc) * sizeof(char *));
free(argv);
argv = nargv;
}
}
return argv;
}