home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / unix / volume4 / fmtr / fgetsmod.c < prev    next >
Encoding:
C/C++ Source or Header  |  1986-11-30  |  1.6 KB  |  65 lines

  1. #ifndef lint
  2. static char rcsid[] = "$Header: fgetsmod.c,v 1.3 86/05/05 14:19:17 root Exp $";
  3. #endif
  4.  
  5. #include    <stdio.h>
  6.  
  7. #define TOOLONG -2
  8.  
  9. /* New and improved version of fgets.  Unlike original, eats up extra chars.
  10.  * fgets1 will read n - 1 characters, or up to a new line, whichever
  11.  * comes first, from stream iop into string s.  The last character read
  12.  * into s is followed by a null character.
  13.  *
  14.  * It deals with all possibilities.  If line ends with newline or have
  15.  * isolated EOF, no problem.  Otherwise, it will insert a newline and eat
  16.  * any excess characters.  Hence guarantees line ending with newline
  17.  * followed by null.
  18.  *
  19.  * It returns:
  20.  *   1.  NULL at end of file, for compatible with fgets.
  21.  *   2.  TOOLONG if line is too long.
  22.  *       This is usable as a warning.
  23.  *   3.  Length of line, excluding null (like strlen), otherwise.
  24.  *       This is useful in the usual case when line is read uneventfully.
  25.  */
  26.  
  27. fgetsmod(s, n, iop)
  28. char *s;
  29. register FILE *iop;
  30. {
  31.     register c;
  32.     register char *cs;
  33.  
  34.     cs = s;
  35.  
  36.     while (--n > 0 && (c = getc(iop)) != EOF) {
  37.     *cs++ = c;
  38.     if (c == '\n')
  39.         break;
  40.     }
  41.  
  42.     if (c == '\n') {    /* normal ending, commonest case */
  43.     *cs = '\0';
  44.     return (cs - s);
  45.     }
  46.  
  47.     if ((c == EOF) && (cs == s))  /* isolated EOF, second commonest case */
  48.     return (NULL);
  49.  
  50.     if (n == 0) {    /* line too long */
  51.     *cs = '\0';
  52.     *(--cs) = '\n';    /* put in missing newline */
  53.     while ((c = getc(iop)) != EOF && c != '\n')    /* eat up extra chars */
  54.         ;
  55.     return (TOOLONG);
  56.     }
  57.  
  58.     if (c == EOF) {    /* final line has no newline -- rare */
  59.     *cs++ = '\n';
  60.     *cs = '\0';
  61.     return (cs - s);    /* pretend all was OK */
  62.     }
  63.     /* NOTREACHED */
  64. }
  65.