Update build system to Autoconf 2.58, Automake 1.7, gettext 0.12.1.
[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., 59 Temple Place - Suite 330, Boston, MA
18    02111-1307, USA. */
19
20 #include <config.h>
21 #include <assert.h>
22 #include <stddef.h>
23 #include <stdio.h>
24 #include "common.h"
25
26 /* Reads a DELIMITER-separated field of any length from file STREAM.
27    *LINEPTR is a malloc'd string of size N; if *LINEPTR is NULL, it is
28    allocated.  *LINEPTR is allocated/enlarged as necessary.  Returns
29    -1 if at eof when entered; otherwise eof causes return of string
30    without a terminating DELIMITER.  Normally DELIMITER is the last
31    character in *LINEPTR on return (besides the null character which
32    is always present).  Returns number of characters read, including
33    terminating field delimiter if present. */
34 long
35 getdelim (char **lineptr, size_t *n, int delimiter, FILE *stream)
36 {
37   /* Number of characters stored in *lineptr so far. */
38   size_t len;
39
40   /* Last character read. */
41   int c;
42
43   if (*lineptr == NULL || *n < 2)
44     {
45       *lineptr = xrealloc (*lineptr, 128);
46       *n = 128;
47     }
48   assert (*n > 0);
49
50   len = 0;
51   c = getc (stream);
52   if (c == EOF)
53     return -1;
54   while (1)
55     {
56       if (len + 1 >= *n)
57         {
58           *n *= 2;
59           *lineptr = xrealloc (*lineptr, *n);
60         }
61       (*lineptr)[len++] = c;
62
63       if (c == delimiter)
64         break;
65
66       c = getc (stream);
67       if (c == EOF)
68         break;
69     }
70   (*lineptr)[len] = '\0';
71   return len;
72 }