1 /* getdelim.c --- Implementation of replacement getdelim function. 2 Copyright (C) 1994, 1996, 1997, 1998, 2001, 2003, 2005 Free 3 Software Foundation, Inc. 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, or (at 8 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., 51 Franklin Street, Fifth Floor, Boston, MA 18 02110-1301, USA. */ 19 #include <sys/cdefs.h> 20 __RCSID("$NetBSD: getdelim.c,v 1.2 2016/05/17 14:00:09 christos Exp $"); 21 22 23 /* Ported from glibc by Simon Josefsson. */ 24 25 #ifdef HAVE_CONFIG_H 26 # include <config.h> 27 #endif 28 29 #include <stdlib.h> 30 #include <errno.h> 31 32 #include "getdelim.h" 33 34 #if !HAVE_FLOCKFILE 35 # undef flockfile 36 # define flockfile(x) ((void) 0) 37 #endif 38 #if !HAVE_FUNLOCKFILE 39 # undef funlockfile 40 # define funlockfile(x) ((void) 0) 41 #endif 42 43 /* Read up to (and including) a DELIMITER from FP into *LINEPTR (and 44 NUL-terminate it). *LINEPTR is a pointer returned from malloc (or 45 NULL), pointing to *N characters of space. It is realloc'ed as 46 necessary. Returns the number of characters read (not including 47 the null terminator), or -1 on error or EOF. */ 48 49 ssize_t 50 getdelim (char **lineptr, size_t *n, int delimiter, FILE *fp) 51 { 52 int result = 0; 53 ssize_t cur_len = 0; 54 ssize_t len; 55 56 if (lineptr == NULL || n == NULL || fp == NULL) 57 { 58 errno = EINVAL; 59 return -1; 60 } 61 62 flockfile (fp); 63 64 if (*lineptr == NULL || *n == 0) 65 { 66 *n = 120; 67 *lineptr = (char *) malloc (*n); 68 if (*lineptr == NULL) 69 { 70 result = -1; 71 goto unlock_return; 72 } 73 } 74 75 for (;;) 76 { 77 char *t; 78 int i; 79 80 i = getc (fp); 81 if (i == EOF) 82 { 83 result = -1; 84 break; 85 } 86 87 /* Make enough space for len+1 (for final NUL) bytes. */ 88 if (cur_len + 1 >= *n) 89 { 90 size_t needed = 2 * (cur_len + 1) + 1; /* Be generous. */ 91 char *new_lineptr; 92 93 if (needed < cur_len) 94 { 95 result = -1; 96 goto unlock_return; 97 } 98 99 new_lineptr = (char *) realloc (*lineptr, needed); 100 if (new_lineptr == NULL) 101 { 102 result = -1; 103 goto unlock_return; 104 } 105 106 *lineptr = new_lineptr; 107 *n = needed; 108 } 109 110 (*lineptr)[cur_len] = i; 111 cur_len++; 112 113 if (i == delimiter) 114 break; 115 } 116 (*lineptr)[cur_len] = '\0'; 117 result = cur_len ? cur_len : result; 118 119 unlock_return: 120 funlockfile (fp); 121 return result; 122 } 123