
Untitled
By: a guest on
May 11th, 2012 | syntax:
None | size: 1.60 KB | hits: 11 | expires: Never
/*!
* \file gets_ws.c
*
* \author Andrew Poelstra
*
* ioutils version 1.0.
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
int gets_ws (char *buff, size_t *count, size_t maxlen, char stop_c, FILE *fh);
/*!
* \brief Reads from \c fh into \c buff.
*
* \c buff may be \c NULL, in which case characters are discarded, up until it reaches
* either \c stop_c or whitespace.\n
* In the special case that the first character is a quote, it will simply
* read everything until it reaches an end quote.\n
* Unless \c buff is \c NULL, it reads at most (maxlen-1) characters and null-terminates
* \c buff.\n
* If \c count is non-NULL, it will be filled with the number of characters read.
* \n
* \retval Returns 0 on success or \c EOF on error.
*/
int
gets_ws (char *buff, size_t *count, size_t maxlen, char stop_c, FILE *fh)
{
size_t i = 0;
int err = (fh == NULL);
int stop_white = 1;
int ch = err ? EOF : getc (fh);
int pch = ch;
switch (ch)
{
case '\"':
case '\'':
case '`':
stop_white = 0;
stop_c = ch;
break;
case EOF:
err = 1;
}
while ((!stop_white || !isspace (ch)) &&
(!buff || i < maxlen) &&
(ch != stop_c || pch == '\\'))
{
pch = ch;
if (buff && i < maxlen)
buff[i++] = ch;
if (ch == EOF)
{
err = (ch == EOF);
ch = stop_c;
} else {
ch = getc (fh);
}
++i;
}
if (count != NULL)
{
*count = i;
}
/* We need to check in case maxlen is 0. */
if (buff && maxlen)
{
buff[i] = 0;
}
ungetc (ch, fh);
return err ? EOF : 0;
}
/* EOF */