1 |
#ifndef lint |
2 |
static const char RCSid[] = "$Id: fgetword.c,v 2.7 2017/04/09 21:33:24 greg Exp $"; |
3 |
#endif |
4 |
/* |
5 |
* Read white space separated words from stream |
6 |
* |
7 |
* External symbols declared in rtio.h |
8 |
*/ |
9 |
|
10 |
#include "copyright.h" |
11 |
|
12 |
#include "rtio.h" |
13 |
|
14 |
#include <ctype.h> |
15 |
|
16 |
|
17 |
char * |
18 |
fgetword( /* get (quoted) word up to n-1 characters */ |
19 |
char *s, |
20 |
int n, |
21 |
FILE *fp |
22 |
) |
23 |
{ |
24 |
int quote = '\0'; |
25 |
char *cp; |
26 |
int c; |
27 |
/* sanity checks */ |
28 |
if ((s == NULL) | (n < 2)) |
29 |
return(NULL); |
30 |
/* skip initial white space */ |
31 |
do |
32 |
c = getc(fp); |
33 |
while (isspace(c)); |
34 |
/* check for quote */ |
35 |
if ((c == '"') | (c == '\'')) { |
36 |
quote = c; |
37 |
c = getc(fp); |
38 |
} |
39 |
/* get actual word */ |
40 |
cp = s; |
41 |
while (c != EOF && !(quote ? c==quote : isspace(c))) { |
42 |
if (--n <= 0) /* check length limit */ |
43 |
break; |
44 |
*cp++ = c; |
45 |
c = getc(fp); |
46 |
} |
47 |
*cp = '\0'; |
48 |
if (c == EOF) { /* hit end-of-file? */ |
49 |
if (cp == s) /* and got nothing? */ |
50 |
return(NULL); |
51 |
} else if (!quote) /* replace white character */ |
52 |
ungetc(c, fp); |
53 |
return(s); |
54 |
} |