getline.c revision 42542f5f
1#include <stdio.h> 2#include <stdlib.h> 3#include <errno.h> 4 5extern int getline(char **line, size_t *len, FILE *file); 6 7int getline(char **line, size_t *len, FILE *file) 8{ 9 char *ptr, *end; 10 int c; 11 12 if (*line == NULL) { 13 errno = EINVAL; 14 if (*len == 0) 15 *line = malloc(4096); 16 if (*line == NULL) 17 return -1; 18 19 *len = 4096; 20 } 21 22 ptr = *line; 23 end = *line + *len; 24 25 while ((c = fgetc(file)) != EOF) { 26 if (ptr + 1 >= end) { 27 char *newline; 28 int offset; 29 30 newline = realloc(*line, *len + 4096); 31 if (newline == NULL) 32 return -1; 33 34 offset = ptr - *line; 35 36 *line = newline; 37 *len += 4096; 38 39 ptr = *line + offset; 40 end = *line + *len; 41 } 42 43 *ptr++ = c; 44 if (c == '\n') { 45 *ptr = '\0'; 46 return ptr - *line; 47 } 48 } 49 *ptr = '\0'; 50 return -1; 51} 52