1 /* $Id: compat_getline.c,v 1.2 2020/06/15 01:37:14 schwarze Exp $ */ 2 /* 3 * Copyright (c) 2015 Ingo Schwarze <schwarze@openbsd.org> 4 * 5 * Permission to use, copy, modify, and distribute this software for any 6 * purpose with or without fee is hereby granted, provided that the above 7 * copyright notice and this permission notice appear in all copies. 8 * 9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 16 */ 17 #include "config.h" 18 19 #include <sys/types.h> 20 #include <errno.h> 21 #include <stdio.h> 22 #include <stdlib.h> 23 24 ssize_t 25 getline(char **buf, size_t *bufsz, FILE *fp) 26 { 27 char *nbuf; 28 size_t nbufsz, pos; 29 int c; 30 31 if (buf == NULL || bufsz == NULL) { 32 errno = EINVAL; 33 return -1; 34 } 35 36 if (*buf == NULL) 37 *bufsz = 0; 38 else 39 **buf = '\0'; 40 41 pos = 0; 42 for (;;) { 43 if (pos + 1 >= *bufsz) { 44 nbufsz = *bufsz ? *bufsz * 2 : BUFSIZ; 45 if ((nbuf = realloc(*buf, nbufsz)) == NULL) 46 return -1; 47 *buf = nbuf; 48 *bufsz = nbufsz; 49 } 50 if ((c = fgetc(fp)) == EOF) { 51 (*buf)[pos] = '\0'; 52 return pos > 0 && feof(fp) ? (ssize_t)pos : -1; 53 } 54 (*buf)[pos++] = c; 55 (*buf)[pos] = '\0'; 56 if (c == '\n') 57 return pos; 58 } 59 } 60