Undo over-zealous version bump.
[gliv.git] / lib / getdelim.c
blob0407c8ef0e8dc1ec7e03cddc09fadc7349eac204
1 /* Taken from uClibc and adapted to GLiv */
3 /* Copyright (C) 2004 Manuel Novoa III <mjn3@codepoet.org>
5 * GNU Library General Public License (LGPL) version 2 or later.
7 * Dedicated to Toni. See uClibc/DEDICATION.mjn3 for details.
8 */
10 #include "stdio.h"
11 #include "stdlib.h"
12 #include "getdelim.h"
14 /* Note: There is a defect in this function. (size_t vs long). */
16 /* glibc function --
17 * Return -1 if error or EOF prior to any chars read.
18 * Return number of chars read (including possible delimiter but not
19 * the terminating nul) otherwise.
21 * NOTE: If we need to allocate a buffer, we do so prior to attempting
22 * a reading. So space may be allocated even if initially at EOF.
24 #define GETDELIM_GROWBY 64
25 long getdelim(char ** lineptr, size_t * n,
26 int delimiter, FILE * stream)
28 char *buf;
29 long pos = -1;
30 int c;
32 if (lineptr && n && stream) {
33 if (!(buf = *lineptr)) { /* If passed NULL for buffer, */
34 *n = 0; /* ignore value passed and treat size as 0. */
37 /* Within the loop, pos is actually the current buffer index + 2,
38 * because we want to make sure we have enough space to store
39 * an additional char plus a nul terminator.
41 pos = 1;
43 do {
44 if (pos >= *n) {
45 if (!(buf = realloc(buf, *n + GETDELIM_GROWBY))) {
46 pos = -1;
47 break;
49 *n += GETDELIM_GROWBY;
50 *lineptr = buf;
53 if ((c = fgetc(stream)) != EOF) {
54 buf[++pos - 2] = c;
55 if (c != delimiter) {
56 continue;
60 /* We're done, so correct pos back to being the current index. */
61 if ((pos -= 2) >= 0) {
62 buf[++pos] = 0;
64 break;
66 } while (1);
69 return pos;