getlines.c (924B)
1 /* See LICENSE file for copyright and license details. */ 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 6 #include "../text.h" 7 #include "../util.h" 8 9 void 10 getlines(FILE *fp, struct linebuf *b) 11 { 12 char *line = NULL; 13 size_t size = 0, linelen = 0; 14 ssize_t len; 15 16 while ((len = getline(&line, &size, fp)) > 0) { 17 if (++b->nlines > b->capacity) { 18 b->capacity += 512; 19 b->lines = erealloc(b->lines, b->capacity * sizeof(*b->lines)); 20 } 21 linelen = len; 22 b->lines[b->nlines - 1].data = memcpy(emalloc(linelen + 1), line, linelen + 1); 23 b->lines[b->nlines - 1].len = linelen; 24 } 25 free(line); 26 if (b->lines && b->nlines && linelen && b->lines[b->nlines - 1].data[linelen - 1] != '\n') { 27 b->lines[b->nlines - 1].data = erealloc(b->lines[b->nlines - 1].data, linelen + 2); 28 b->lines[b->nlines - 1].data[linelen] = '\n'; 29 b->lines[b->nlines - 1].data[linelen + 1] = '\0'; 30 b->lines[b->nlines - 1].len++; 31 } 32 }