14 |
|
#include <ctype.h> |
15 |
|
|
16 |
|
|
17 |
+ |
#define isquote(c) (((c) == '"') | ((c) == '\'')) |
18 |
+ |
|
19 |
+ |
|
20 |
|
char * |
21 |
< |
fgetword(s, n, fp) /* get (quoted) word up to n-1 characters */ |
22 |
< |
char *s; |
23 |
< |
int n; |
24 |
< |
register FILE *fp; |
21 |
> |
fgetword( /* get (quoted) word up to n-1 characters */ |
22 |
> |
char *s, |
23 |
> |
int n, |
24 |
> |
FILE *fp |
25 |
> |
) |
26 |
|
{ |
27 |
|
int quote = '\0'; |
28 |
< |
register char *cp; |
29 |
< |
register int c; |
28 |
> |
char *cp; |
29 |
> |
int c; |
30 |
> |
/* sanity checks */ |
31 |
> |
if ((s == NULL) | (n < 2)) |
32 |
> |
return(NULL); |
33 |
|
/* skip initial white space */ |
34 |
|
do |
35 |
|
c = getc(fp); |
36 |
|
while (isspace(c)); |
37 |
|
/* check for quote */ |
38 |
< |
if ((c == '"') | (c == '\'')) { |
38 |
> |
if (isquote(c)) { |
39 |
|
quote = c; |
40 |
|
c = getc(fp); |
41 |
|
} |
42 |
< |
/* check for end of file */ |
43 |
< |
if (c == EOF) |
44 |
< |
return(NULL); |
45 |
< |
/* get actual word */ |
46 |
< |
cp = s; |
47 |
< |
do { |
48 |
< |
if (--n <= 0) /* check length limit */ |
49 |
< |
break; |
50 |
< |
*cp++ = c; |
51 |
< |
c = getc(fp); |
52 |
< |
} while (c != EOF && !(quote ? c==quote : isspace(c))); |
42 |
> |
cp = s; /* get actual word */ |
43 |
> |
while (c != EOF) { |
44 |
> |
if (c == quote) /* end quote? */ |
45 |
> |
quote = '\0'; |
46 |
> |
else if (!quote && isquote(c)) |
47 |
> |
quote = c; /* started new quote */ |
48 |
> |
else { |
49 |
> |
if (!quote && isspace(c)) |
50 |
> |
break; /* end of word */ |
51 |
> |
if (--n <= 0) |
52 |
> |
break; /* hit length limit */ |
53 |
> |
*cp++ = c; |
54 |
> |
} |
55 |
> |
c = getc(fp); /* get next character */ |
56 |
> |
} |
57 |
|
*cp = '\0'; |
58 |
< |
if ((c != EOF) & (!quote)) /* replace space */ |
59 |
< |
ungetc(c, fp); |
58 |
> |
if ((c == EOF) & (cp == s)) /* hit end-of-file? */ |
59 |
> |
return(NULL); |
60 |
|
return(s); |
61 |
|
} |