--- ray/src/common/fgetword.c 2003/02/25 02:47:21 2.3 +++ ray/src/common/fgetword.c 2023/02/10 04:32:19 2.9 @@ -1,50 +1,61 @@ #ifndef lint -static const char RCSid[] = "$Id: fgetword.c,v 2.3 2003/02/25 02:47:21 greg Exp $"; +static const char RCSid[] = "$Id: fgetword.c,v 2.9 2023/02/10 04:32:19 greg Exp $"; #endif /* * Read white space separated words from stream * - * External symbols declared in standard.h + * External symbols declared in rtio.h */ #include "copyright.h" -#include +#include "rtio.h" #include +#define isquote(c) (((c) == '"') | ((c) == '\'')) + + char * -fgetword(s, n, fp) /* get (quoted) word up to n-1 characters */ -char *s; -int n; -register FILE *fp; +fgetword( /* get (quoted) word up to n-1 characters */ + char *s, + int n, + FILE *fp +) { int quote = '\0'; - register char *cp; - register int c; + char *cp; + int c; + /* sanity checks */ + if ((s == NULL) | (n < 2)) + return(NULL); /* skip initial white space */ do c = getc(fp); while (isspace(c)); /* check for quote */ - if ((c == '"' | c == '\'')) { + if (isquote(c)) { quote = c; c = getc(fp); } - /* check for end of file */ - if (c == EOF) - return(NULL); - /* get actual word */ - cp = s; - do { - if (--n <= 0) /* check length limit */ - break; - *cp++ = c; - c = getc(fp); - } while (c != EOF && !(quote ? c==quote : isspace(c))); + cp = s; /* get actual word */ + while (c != EOF) { + if (c == quote) /* end quote? */ + quote = '\0'; + else if (!quote && isquote(c)) + quote = c; /* started new quote */ + else { + if (!quote && isspace(c)) + break; /* end of word */ + if (--n <= 0) + break; /* hit length limit */ + *cp++ = c; + } + c = getc(fp); /* get next character */ + } *cp = '\0'; - if ((c != EOF & !quote)) /* replace space */ - ungetc(c, fp); + if ((c == EOF) & (cp == s)) /* hit end-of-file? */ + return(NULL); return(s); }