/* $NetBSD: getline.c,v 1.2 2014/09/16 17:23:50 christos Exp $ */12/*-3* Copyright (c) 2011 The NetBSD Foundation, Inc.4* All rights reserved.5*6* This code is derived from software contributed to The NetBSD Foundation7* by Christos Zoulas.8*9* Redistribution and use in source and binary forms, with or without10* modification, are permitted provided that the following conditions11* are met:12* 1. Redistributions of source code must retain the above copyright13* notice, this list of conditions and the following disclaimer.14* 2. Redistributions in binary form must reproduce the above copyright15* notice, this list of conditions and the following disclaimer in the16* documentation and/or other materials provided with the distribution.17*18* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS19* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED20* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR21* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS22* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR23* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF24* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS25* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN26* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)27* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE28* POSSIBILITY OF SUCH DAMAGE.29*/3031#include "file.h"32#if !HAVE_GETLINE33#include <stdlib.h>34#include <stdio.h>35#include <unistd.h>36#include <errno.h>37#include <string.h>3839file_public ssize_t40getdelim(char **buf, size_t *bufsiz, int delimiter, FILE *fp)41{42char *ptr, *eptr;434445if (*buf == NULL || *bufsiz == 0) {46*bufsiz = BUFSIZ;47if ((*buf = malloc(*bufsiz)) == NULL)48return -1;49}5051for (ptr = *buf, eptr = *buf + *bufsiz;;) {52int c = fgetc(fp);53if (c == -1) {54if (feof(fp)) {55ssize_t diff = (ssize_t)(ptr - *buf);56if (diff != 0) {57*ptr = '\0';58return diff;59}60}61return -1;62}63*ptr++ = c;64if (c == delimiter) {65*ptr = '\0';66return ptr - *buf;67}68if (ptr + 2 >= eptr) {69char *nbuf;70size_t nbufsiz = *bufsiz * 2;71ssize_t d = ptr - *buf;72if ((nbuf = realloc(*buf, nbufsiz)) == NULL)73return -1;74*buf = nbuf;75*bufsiz = nbufsiz;76eptr = nbuf + nbufsiz;77ptr = nbuf + d;78}79}80}8182file_public ssize_t83getline(char **buf, size_t *bufsiz, FILE *fp)84{85return getdelim(buf, bufsiz, '\n', fp);86}8788#endif8990#ifdef TEST91int92main(int argc, char *argv[])93{94char *p = NULL;95ssize_t len;96size_t n = 0;9798while ((len = getline(&p, &n, stdin)) != -1)99(void)printf("%" SIZE_T_FORMAT "d %s", len, p);100free(p);101return 0;102}103#endif104105106