-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathgetw.c
141 lines (130 loc) · 2.39 KB
/
getw.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/*
* getwordx public domain library v.2.0
* (c) 1995,1996,1997 <[email protected]>
*/
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <sys/types.h>
#include <stddef.h>
#include "Config.h"
#include "sys.h"
#include "tools.h"
char *getwordx2 (const char *src, int n, int flags, char *fldsep, char *fldskip)
{
char *dest;
char quoted = 0;
int i;
if (!src) return NULL;
dest = xstrdup(src);
while (1)
{
while (*src && strchr (fldskip, *src))
++src;
if (!*src || ((flags & GWX_HASH) && *src == '#'))
{
free (dest);
return NULL;
}
for (i = 0;; ++i, ++src)
{
if ((flags & GWX_NOESC) == 0 && *src == '\\')
{
int base = 8, ch = 0;
++src;
if (!isdigit (*src) && *src != 'x' && *src != 'X')
{
switch (*src)
{
case 'a': /* bell */
ch = '\a';
break;
case 'b': /* bksp */
ch = '\b';
break;
case 'f': /* ff */
ch = '\f';
break;
case 'n': /* lf */
ch = '\n';
break;
case 'r': /* cr */
ch = '\r';
break;
case 't': /* tab */
ch = '\t';
break;
case 'E': /* ESC */
ch = 0033;
break;
default:
ch = *src;
break;
}
++src;
}
else
{
if (toupper (*src) == 'X')
{
++src;
base = 16;
}
for (; isxdigit (*src); ++src)
{
if (isdigit (*src))
ch = ch * base + *src - '0';
else if (base == 16)
ch = ch * base + tolower (*src) - 'a' + 0xa;
else
break;
}
}
dest[i] = (char) ch;
--src;
}
else if (!*src || *src == '\n' || *src == '\r')
break;
else if (*src == '\"')
{
quoted = ~quoted;
i--;
}
else if (strchr (fldsep, *src) && !quoted)
break;
else if (*src == '%' && (flags & GWX_SUBST))
{
++src;
if (*src == '%')
{
dest[i] = '%';
}
else
{
char varname[MAX_ENV_VAR_NAME + 1];
char *var;
unsigned k;
for (k = 0; k < sizeof (varname) &&
!isspace (*src) &&
*src != '%'; ++k)
varname[k] = toupper (src++[0]);
varname[k] = 0;
if ((var = getenv (varname)) == 0)
var = "";
dest = xrealloc (dest, strlen (src) + strlen (var) + 1);
strcpy (dest + i, var);
i += strlen (var) - 1;
}
}
else
dest[i] = *src;
}
if (--n == 0)
{
dest[i] = 0;
return dest;
}
if (*src && strchr (fldsep, *src))
++src;
}
}