getline.c revision 1ba0013f21e1953ae4a59cdf61562fbe843077e9
2880N/A#include <sys/types.h>
2880N/A#include <stdio.h>
2880N/A#include <stdlib.h>
2880N/A#include <string.h>
2880N/A
2880N/A/*
2880N/A * Emulate glibc getline() via BSD fgetln().
2880N/A * Note that outsize is not changed unless memory is allocated.
2880N/A */
2880N/Assize_t
2880N/Agetline(char **outbuf, size_t *outsize, FILE *fp)
2880N/A{
2880N/A size_t len;
2880N/A char *buf;
2880N/A buf = fgetln(fp, &len);
2880N/A
2880N/A if (buf == NULL)
2880N/A return (-1);
2880N/A
2880N/A /* Assumes realloc() accepts NULL for ptr (C99) */
2880N/A if (*outbuf == NULL || *outsize < len + 1) {
2880N/A void *tmp = realloc(*outbuf, len + 1);
6033N/A if (tmp == NULL)
2880N/A return (-1);
4070N/A *outbuf = tmp;
2880N/A *outsize = len + 1;
2880N/A }
2880N/A memcpy(*outbuf, buf, len);
6033N/A (*outbuf)[len] = '\0';
2880N/A return (len);
2880N/A}
2880N/A