1 /* getdelim.c --- Implementation of replacement getdelim function.
2 Copyright (C) 1994, 1996-1998, 2001, 2003, 2005-2023 Free Software
5 This file is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as
7 published by the Free Software Foundation; either version 2.1 of the
8 License, or (at your option) any later version.
10 This file is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18 /* Ported from glibc by Simon Josefsson. */
20 /* Don't use __attribute__ __nonnull__ in this compilation unit. Otherwise gcc
21 optimizes away the lineptr == NULL || n == NULL || fp == NULL tests below. */
22 #define _GL_ARG_NONNULL(params)
34 # define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2))
38 # include "unlocked-io.h"
39 # define getc_maybe_unlocked(fp) getc(fp)
40 #elif !HAVE_FLOCKFILE || !HAVE_FUNLOCKFILE || !HAVE_DECL_GETC_UNLOCKED
43 # define flockfile(x) ((void) 0)
44 # define funlockfile(x) ((void) 0)
45 # define getc_maybe_unlocked(fp) getc(fp)
47 # define getc_maybe_unlocked(fp) getc_unlocked(fp)
53 #if defined _WIN32 && ! defined __CYGWIN__
54 /* Avoid errno problem without using the realloc module; see:
55 https://lists.gnu.org/r/bug-gnulib/2016-08/msg00025.html */
60 /* Read up to (and including) a DELIMITER from FP into *LINEPTR (and
61 NUL-terminate it). *LINEPTR is a pointer returned from malloc (or
62 NULL), pointing to *N characters of space. It is realloc'ed as
63 necessary. Returns the number of characters read (not including
64 the null terminator), or -1 on error or EOF. */
67 getdelim (char **lineptr
, size_t *n
, int delimiter
, FILE *fp
)
72 if (lineptr
== NULL
|| n
== NULL
|| fp
== NULL
)
80 if (*lineptr
== NULL
|| *n
== 0)
84 new_lineptr
= (char *) realloc (*lineptr
, *n
);
85 if (new_lineptr
== NULL
)
91 *lineptr
= new_lineptr
;
98 i
= getc_maybe_unlocked (fp
);
105 /* Make enough space for len+1 (for final NUL) bytes. */
106 if (cur_len
+ 1 >= *n
)
109 SSIZE_MAX
< SIZE_MAX
? (size_t) SSIZE_MAX
+ 1 : SIZE_MAX
;
110 size_t needed
= 2 * *n
+ 1; /* Be generous. */
113 if (needed_max
< needed
)
115 if (cur_len
+ 1 >= needed
)
122 new_lineptr
= (char *) realloc (*lineptr
, needed
);
123 if (new_lineptr
== NULL
)
130 *lineptr
= new_lineptr
;
134 (*lineptr
)[cur_len
] = i
;
140 (*lineptr
)[cur_len
] = '\0';
141 result
= cur_len
? cur_len
: result
;
144 funlockfile (fp
); /* doesn't set errno */