1
2
3
4
5
6
7
8
9
10#include <assert.h>
11#include <stdio.h>
12
13
14#define MIN_CHUNK 64
15
16
17
18
19
20
21
22static int getstr(char **lineptr, size_t *n, FILE *stream,
23 char terminator, size_t offset)
24{
25 int nchars_avail;
26 char *read_pos;
27 int ret;
28
29 if (!lineptr || !n || !stream)
30 return -1;
31
32 if (!*lineptr) {
33 *n = MIN_CHUNK;
34 *lineptr = malloc(*n);
35 if (!*lineptr)
36 return -1;
37 }
38
39 nchars_avail = *n - offset;
40 read_pos = *lineptr + offset;
41
42 for (;;) {
43 register int c = getc(stream);
44
45
46
47
48
49 assert(*n - nchars_avail == read_pos - *lineptr);
50 if (nchars_avail < 2) {
51 if (*n > MIN_CHUNK)
52 *n *= 2;
53 else
54 *n += MIN_CHUNK;
55
56 nchars_avail = *n + *lineptr - read_pos;
57 *lineptr = realloc(*lineptr, *n);
58 if (!*lineptr)
59 return -1;
60 read_pos = *n - nchars_avail + *lineptr;
61 assert(*n - nchars_avail == read_pos - *lineptr);
62 }
63
64 if (c == EOF || ferror (stream)) {
65
66 if (read_pos == *lineptr)
67 return -1;
68 else
69 break;
70 }
71
72 *read_pos++ = c;
73 nchars_avail--;
74
75 if (c == terminator)
76
77 break;
78 }
79
80
81 *read_pos = '\0';
82
83 ret = read_pos - (*lineptr + offset);
84 return ret;
85}
86
87int getline (char **lineptr, size_t *n, FILE *stream)
88{
89 return getstr(lineptr, n, stream, '\n', 0);
90}
91