1428d7b3dSmrg#include <stdio.h> 2428d7b3dSmrg#include <stdlib.h> 3428d7b3dSmrg#include <errno.h> 4428d7b3dSmrg 5428d7b3dSmrgextern int getline(char **line, size_t *len, FILE *file); 6428d7b3dSmrg 7428d7b3dSmrgint getline(char **line, size_t *len, FILE *file) 8428d7b3dSmrg{ 9428d7b3dSmrg char *ptr, *end; 10428d7b3dSmrg int c; 11428d7b3dSmrg 12428d7b3dSmrg if (*line == NULL) { 13428d7b3dSmrg errno = EINVAL; 14428d7b3dSmrg if (*len == 0) 15428d7b3dSmrg *line = malloc(4096); 16428d7b3dSmrg if (*line == NULL) 17428d7b3dSmrg return -1; 18428d7b3dSmrg 19428d7b3dSmrg *len = 4096; 20428d7b3dSmrg } 21428d7b3dSmrg 22428d7b3dSmrg ptr = *line; 23428d7b3dSmrg end = *line + *len; 24428d7b3dSmrg 25428d7b3dSmrg while ((c = fgetc(file)) != EOF) { 26428d7b3dSmrg if (ptr + 1 >= end) { 27428d7b3dSmrg char *newline; 28428d7b3dSmrg int offset; 29428d7b3dSmrg 30428d7b3dSmrg newline = realloc(*line, *len + 4096); 31428d7b3dSmrg if (newline == NULL) 32428d7b3dSmrg return -1; 33428d7b3dSmrg 34428d7b3dSmrg offset = ptr - *line; 35428d7b3dSmrg 36428d7b3dSmrg *line = newline; 37428d7b3dSmrg *len += 4096; 38428d7b3dSmrg 39428d7b3dSmrg ptr = *line + offset; 40428d7b3dSmrg end = *line + *len; 41428d7b3dSmrg } 42428d7b3dSmrg 43428d7b3dSmrg *ptr++ = c; 44428d7b3dSmrg if (c == '\n') { 45428d7b3dSmrg *ptr = '\0'; 46428d7b3dSmrg return ptr - *line; 47428d7b3dSmrg } 48428d7b3dSmrg } 49428d7b3dSmrg *ptr = '\0'; 50428d7b3dSmrg return -1; 51428d7b3dSmrg} 52