Added all of the MH sources, including RCS files, in
[mmh] / docs / historical / mh-6.8.5 / sbr / vfgets.c
1 /* vfgets.c - virtual fgets */
2 #ifndef       lint
3 static char ident[] = "@(#)$Id: vfgets.c,v 1.3 1992/12/15 00:20:22 jromine Exp $";
4 #endif  /*        lint */
5
6 #include "../h/mh.h"
7 #include <stdio.h>
8
9
10 #define QUOTE   '\\'
11
12
13 int     vfgets (in, bp)
14 register FILE *in;
15 register char  **bp;
16 {
17     register int    toggle;
18     register char  *cp,
19                    *dp,
20                    *ep,
21                    *fp;
22     static int  len = 0;
23     static char *pp = NULL;
24
25     if (pp == NULL)
26         if ((pp = malloc ((unsigned) (len = BUFSIZ))) == NULL)
27             adios (NULLCP, "unable to allocate string storage");
28
29     for (ep = (cp = pp) + len - 1;;) {
30         if (fgets (cp, ep - cp + 1, in) == NULL) {
31             if (cp != pp) {
32                 *bp = pp;
33                 return OK;
34             }
35             return (ferror (in) && !feof (in) ? NOTOK : DONE);
36         }
37
38         if ((dp = cp + strlen (cp) - 2) < cp || *dp != QUOTE) {
39 wrong_guess: ;
40             if (cp > ++dp)
41                 adios (NULLCP, "vfgets() botch -- you lose big");
42             if (*dp == '\n') {
43                 *bp = pp;
44                 return OK;
45             }
46             else
47                 cp = ++dp;
48         }
49         else {
50             for (fp = dp - 1, toggle = 0; fp >= cp; fp--)
51                 if (*fp != QUOTE)
52                     break;
53                 else
54                     toggle = !toggle;
55             if (toggle)
56                 goto wrong_guess;
57             if (*++dp == '\n')
58                 *--dp = 0, cp = dp;
59             else
60                 cp = ++dp;
61         }
62
63         if (cp >= ep) {
64             register int curlen = cp - pp;
65
66             if ((dp = realloc (pp, (unsigned) (len += BUFSIZ))) == NULL)
67                 adios (NULLCP, "unable to allocate string storage");
68             else
69                 cp = dp + curlen, ep = (pp = dp) + len - 1;
70         }
71     }
72 }