A
Andrew Poelstra
int gets_ws (char *buff, int maxlen, int sc, FILE *fh);
This function reads up to maxlen characters from fh, stopping when it
encounters whitespace, sc, or EOF. If EOF is encountered, the function
returns EOF.
If buff is NULL, read characters are discarded. Otherwise, they are
put into buff. The function returns the number of characters read or
0 in the case of a NULL buffer.
I use it in my XML parser to read a tag name:
gets_ws (buff, max, '>', fh);
and if it reads max characters (by returning max), I simply delete
the remaining characters:
gets_ws (NULL, 0, '>', fh);
Here is the code:
gets_ws.c:
/* Reads from stream up until first whitespace or sc character. *
* If given a non-NULL buffer, it will fill that. Otherwise, it *
* will simply go through the characters and throw them away. *
* Returns number of characters read or EOF on failure. */
static int gets_ws (char *buff, size_t maxlen, int sc, FILE *fh)
{
int i = 0;
int ch = fgetc (fh);
assert (fh != NULL);
if (buff == NULL)
{
while (!isspace (ch) && ch != sc)
ch = fgetc (fh);
ungetc (ch);
return 0;
}
while (i < (maxlen - 1) && !isspace (ch) && ch != sc)
{
if (ch == EOF)
return EOF;
buff = ch;
++i;
ch = fgetc (fh);
}
ungetc (ch);
return i;
}
Comments or suggestions are welcome.
This function reads up to maxlen characters from fh, stopping when it
encounters whitespace, sc, or EOF. If EOF is encountered, the function
returns EOF.
If buff is NULL, read characters are discarded. Otherwise, they are
put into buff. The function returns the number of characters read or
0 in the case of a NULL buffer.
I use it in my XML parser to read a tag name:
gets_ws (buff, max, '>', fh);
and if it reads max characters (by returning max), I simply delete
the remaining characters:
gets_ws (NULL, 0, '>', fh);
Here is the code:
gets_ws.c:
/* Reads from stream up until first whitespace or sc character. *
* If given a non-NULL buffer, it will fill that. Otherwise, it *
* will simply go through the characters and throw them away. *
* Returns number of characters read or EOF on failure. */
static int gets_ws (char *buff, size_t maxlen, int sc, FILE *fh)
{
int i = 0;
int ch = fgetc (fh);
assert (fh != NULL);
if (buff == NULL)
{
while (!isspace (ch) && ch != sc)
ch = fgetc (fh);
ungetc (ch);
return 0;
}
while (i < (maxlen - 1) && !isspace (ch) && ch != sc)
{
if (ch == EOF)
return EOF;
buff = ch;
++i;
ch = fgetc (fh);
}
ungetc (ch);
return i;
}
Comments or suggestions are welcome.