Changed all the licence notices in all the files.
[pspp-builds.git] / lib / misc / getdelim.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997, 1998 Free Software Foundation, Inc.
3    Written by Ben Pfaff <blp@gnu.org>.
4
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18    02110-1301, USA. */
19
20 #include <config.h>
21 #include <assert.h>
22 #include <stddef.h>
23 #include <stdio.h>
24
25 /* Reads a DELIMITER-separated field of any length from file STREAM.
26    *LINEPTR is a malloc'd string of size N; if *LINEPTR is NULL, it is
27    allocated.  *LINEPTR is allocated/enlarged as necessary.  Returns
28    -1 if at eof when entered; otherwise eof causes return of string
29    without a terminating DELIMITER.  Normally DELIMITER is the last
30    character in *LINEPTR on return (besides the null character which
31    is always present).  Returns number of characters read, including
32    terminating field delimiter if present. */
33 long
34 getdelim (char **lineptr, size_t *n, int delimiter, FILE *stream)
35 {
36   /* Number of characters stored in *lineptr so far. */
37   size_t len;
38
39   /* Last character read. */
40   int c;
41
42   if (*lineptr == NULL || *n < 2)
43     {
44       *lineptr = xrealloc (*lineptr, 128);
45       *n = 128;
46     }
47   assert (*n > 0);
48
49   len = 0;
50   c = getc (stream);
51   if (c == EOF)
52     return -1;
53   while (1)
54     {
55       if (len + 1 >= *n)
56         {
57           *n *= 2;
58           *lineptr = xrealloc (*lineptr, *n);
59         }
60       (*lineptr)[len++] = c;
61
62       if (c == delimiter)
63         break;
64
65       c = getc (stream);
66       if (c == EOF)
67         break;
68     }
69   (*lineptr)[len] = '\0';
70   return len;
71 }