1 /* getndelim2 - Read n characters or less from a stream, stopping at one of up
2 to two specified delimiters.
4 Copyright (C) 1993, 1996, 1997, 1998, 2000, 2003 Free Software
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software Foundation,
19 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
21 /* Originally written by Jan Brittenson, bson@gnu.ai.mit.edu. */
28 #include "getndelim2.h"
32 #include "unlocked-io.h"
34 /* Always add at least this many bytes when extending the buffer. */
38 getndelim2 (char **lineptr, size_t *linesize, size_t offset, size_t limit,
39 int delim1, int delim2, FILE *stream)
41 size_t nbytes_avail; /* Allocated but unused chars in *LINEPTR. */
42 char *read_pos; /* Where we're reading into *LINEPTR. */
44 if (!lineptr || !linesize || !stream)
49 *linesize = MIN_CHUNK;
50 *lineptr = malloc (*linesize);
55 if (*linesize < offset)
58 nbytes_avail = *linesize - offset;
59 read_pos = *lineptr + offset;
63 /* Here always *lineptr + *linesize == read_pos + nbytes_avail. */
71 if (limit != GETNDELIM_NO_LIMIT)
74 /* We always want at least one char left in the buffer, since we
75 always (unless we get an error while reading the first char)
76 NUL-terminate the line buffer. */
80 if (*linesize > MIN_CHUNK)
83 *linesize += MIN_CHUNK;
85 nbytes_avail = *linesize + *lineptr - read_pos;
86 *lineptr = realloc (*lineptr, *linesize);
89 read_pos = *linesize - nbytes_avail + *lineptr;
94 /* Return partial line, if any. */
95 if (read_pos == *lineptr)
104 if (c == delim1 || (delim2 && c == delim2))
105 /* Return the line. */
109 /* Done - NUL terminate and return the number of chars read.
110 At this point we know that nbytes_avail >= 1. */
113 return read_pos - (*lineptr + offset);