Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 11th, 2012  |  syntax: None  |  size: 1.60 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. /*!
  2.  * \file gets_ws.c
  3.  *
  4.  * \author Andrew Poelstra
  5.  *
  6.  * ioutils version 1.0.
  7.  */
  8.  
  9.  
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <stdio.h>
  13. #include <ctype.h>
  14.  
  15.  
  16. int gets_ws (char *buff, size_t *count, size_t maxlen, char stop_c, FILE *fh);
  17.  
  18. /*!
  19.  * \brief Reads from \c fh into \c buff.
  20.  *
  21.  * \c buff may be \c NULL, in which case characters are discarded, up until it reaches
  22.  * either \c stop_c or whitespace.\n
  23.  * In the special case that the first character is a quote, it will simply
  24.  * read everything until it reaches an end quote.\n
  25.  * Unless \c buff is \c NULL, it reads at most (maxlen-1) characters and null-terminates
  26.  * \c buff.\n
  27.  * If \c count is non-NULL, it will be filled with the number of characters read.
  28.  * \n
  29.  * \retval Returns 0 on success or \c EOF on error.
  30.  */
  31. int
  32. gets_ws (char *buff, size_t *count, size_t maxlen, char stop_c, FILE *fh)
  33. {
  34.   size_t i = 0;
  35.   int err = (fh == NULL);
  36.   int stop_white = 1;
  37.   int ch  = err ? EOF : getc (fh);
  38.   int pch = ch;
  39.  
  40.   switch (ch)
  41.   {
  42.     case '\"':
  43.     case '\'':
  44.     case '`':
  45.       stop_white = 0;
  46.       stop_c = ch;
  47.       break;
  48.     case EOF:
  49.       err = 1;
  50.   }
  51.   while ((!stop_white || !isspace (ch)) &&
  52.          (!buff || i < maxlen) &&
  53.          (ch != stop_c || pch == '\\'))
  54.   {
  55.     pch = ch;
  56.     if (buff && i < maxlen)
  57.       buff[i++] = ch;
  58.  
  59.     if (ch == EOF)
  60.     {
  61.       err = (ch == EOF);
  62.       ch = stop_c;
  63.     } else {
  64.       ch = getc (fh);
  65.     }
  66.     ++i;
  67.   }
  68.   if (count != NULL)
  69.   {
  70.     *count = i;
  71.   }
  72.   /* We need to check in case maxlen is 0. */
  73.   if (buff && maxlen)
  74.   {
  75.     buff[i] = 0;
  76.   }
  77.   ungetc (ch, fh);
  78.   return err ? EOF : 0;
  79. }
  80.  
  81.  
  82. /* EOF */