1 /* getdelim.c --- Implementation of replacement getdelim function.
2 Copyright (C) 1994, 1996, 1997, 1998, 2001, 2003, 2005, 2006, 2007,
3 2008, 2009 Free Software Foundation, Inc.
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 3, or (at
8 your option) any later version.
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.
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
20 /* Ported from glibc by Simon Josefsson. */
32 # define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2))
36 # include "unlocked-io.h"
37 # define getc_maybe_unlocked(fp) getc(fp)
38 #elif !HAVE_FLOCKFILE || !HAVE_FUNLOCKFILE || !HAVE_DECL_GETC_UNLOCKED
41 # define flockfile(x) ((void) 0)
42 # define funlockfile(x) ((void) 0)
43 # define getc_maybe_unlocked(fp) getc(fp)
45 # define getc_maybe_unlocked(fp) getc_unlocked(fp)
48 /* Read up to (and including) a DELIMITER from FP into *LINEPTR (and
49 NUL-terminate it). *LINEPTR is a pointer returned from malloc (or
50 NULL), pointing to *N characters of space. It is realloc'ed as
51 necessary. Returns the number of characters read (not including
52 the null terminator), or -1 on error or EOF. */
55 getdelim (char **lineptr, size_t *n, int delimiter, FILE *fp)
60 if (lineptr == NULL || n == NULL || fp == NULL)
68 if (*lineptr == NULL || *n == 0)
72 new_lineptr = (char *) realloc (*lineptr, *n);
73 if (new_lineptr == NULL)
78 *lineptr = new_lineptr;
85 i = getc_maybe_unlocked (fp);
92 /* Make enough space for len+1 (for final NUL) bytes. */
93 if (cur_len + 1 >= *n)
96 SSIZE_MAX < SIZE_MAX ? (size_t) SSIZE_MAX + 1 : SIZE_MAX;
97 size_t needed = 2 * *n + 1; /* Be generous. */
100 if (needed_max < needed)
102 if (cur_len + 1 >= needed)
109 new_lineptr = (char *) realloc (*lineptr, needed);
110 if (new_lineptr == NULL)
116 *lineptr = new_lineptr;
120 (*lineptr)[cur_len] = i;
126 (*lineptr)[cur_len] = '\0';
127 result = cur_len ? (ssize_t) cur_len : result;
130 funlockfile (fp); /* doesn't set errno */