This source file includes following definitions.
- initbuffer
- readlinebuffer
- readlinebuffer_delim
- freebuffer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 #include <config.h>
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/types.h>
27 #include "linebuffer.h"
28 #include "xalloc.h"
29
30 #if USE_UNLOCKED_IO
31 # include "unlocked-io.h"
32 #endif
33
34
35
36 void
37 initbuffer (struct linebuffer *linebuffer)
38 {
39 memset (linebuffer, 0, sizeof *linebuffer);
40 }
41
42 struct linebuffer *
43 readlinebuffer (struct linebuffer *linebuffer, FILE *stream)
44 {
45 return readlinebuffer_delim (linebuffer, stream, '\n');
46 }
47
48
49
50
51
52
53
54
55
56
57
58 struct linebuffer *
59 readlinebuffer_delim (struct linebuffer *linebuffer, FILE *stream,
60 char delimiter)
61 {
62 int c;
63 char *buffer = linebuffer->buffer;
64 char *p = linebuffer->buffer;
65 char *end = buffer + linebuffer->size;
66
67 if (feof (stream))
68 return NULL;
69
70 do
71 {
72 c = getc (stream);
73 if (c == EOF)
74 {
75 if (p == buffer || ferror (stream))
76 return NULL;
77 if (p[-1] == delimiter)
78 break;
79 c = delimiter;
80 }
81 if (p == end)
82 {
83 idx_t oldsize = linebuffer->size;
84 buffer = xpalloc (buffer, &linebuffer->size, 1, -1, 1);
85 p = buffer + oldsize;
86 linebuffer->buffer = buffer;
87 end = buffer + linebuffer->size;
88 }
89 *p++ = c;
90 }
91 while (c != delimiter);
92
93 linebuffer->length = p - buffer;
94 return linebuffer;
95 }
96
97
98
99 void
100 freebuffer (struct linebuffer *linebuffer)
101 {
102 free (linebuffer->buffer);
103 }