1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17#include "libbb.h"
18
19
20
21
22
23
24
25
26
27char* FAST_FUNC bb_get_chunk_with_continuation(FILE *file, int *end, int *lineno)
28{
29 int ch;
30 int idx = 0;
31 char *linebuf = NULL;
32 int linebufsz = 0;
33
34 while ((ch = getc(file)) != EOF) {
35
36 if (idx >= linebufsz) {
37 linebufsz += 256;
38 linebuf = xrealloc(linebuf, linebufsz);
39 }
40 linebuf[idx++] = (char) ch;
41 if (!ch)
42 break;
43 if (end && ch == '\n') {
44 if (lineno == NULL)
45 break;
46 (*lineno)++;
47 if (idx < 2 || linebuf[idx-2] != '\\')
48 break;
49 idx -= 2;
50 }
51 }
52 if (end)
53 *end = idx;
54 if (linebuf) {
55
56
57
58
59
60
61 linebuf = xrealloc(linebuf, idx + 1);
62 linebuf[idx] = '\0';
63 }
64 return linebuf;
65}
66
67char* FAST_FUNC bb_get_chunk_from_file(FILE *file, int *end)
68{
69 return bb_get_chunk_with_continuation(file, end, NULL);
70}
71
72
73char* FAST_FUNC xmalloc_fgets(FILE *file)
74{
75 int i;
76
77 return bb_get_chunk_from_file(file, &i);
78}
79
80char* FAST_FUNC xmalloc_fgetline(FILE *file)
81{
82 int i;
83 char *c = bb_get_chunk_from_file(file, &i);
84
85 if (i && c[--i] == '\n')
86 c[i] = '\0';
87
88 return c;
89}
90
91#if 0
92
93
94
95char* FAST_FUNC xmalloc_fgets(FILE *file)
96{
97 char *res_buf = NULL;
98 size_t res_sz;
99
100 if (getline(&res_buf, &res_sz, file) == -1) {
101 free(res_buf);
102 res_buf = NULL;
103 }
104
105 return res_buf;
106}
107
108char* FAST_FUNC xmalloc_fgetline(FILE *file)
109{
110 char *res_buf = NULL;
111 size_t res_sz;
112
113 res_sz = getline(&res_buf, &res_sz, file);
114
115 if ((ssize_t)res_sz != -1) {
116 if (res_buf[res_sz - 1] == '\n')
117 res_buf[--res_sz] = '\0';
118
119 } else {
120 free(res_buf);
121 res_buf = NULL;
122 }
123 return res_buf;
124}
125
126#endif
127
128#if 0
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148static char* xmalloc_fgets_internal(FILE *file, int *sizep)
149{
150 int len;
151 int idx = 0;
152 char *linebuf = NULL;
153
154 while (1) {
155 char *r;
156
157 linebuf = xrealloc(linebuf, idx + 0x100);
158 r = fgets(&linebuf[idx], 0x100, file);
159 if (!r) {
160
161
162 linebuf[idx] = '\0';
163 break;
164 }
165
166 len = strlen(&linebuf[idx]);
167 idx += len;
168 if (len != 0xff || linebuf[idx - 1] == '\n')
169 break;
170 }
171 *sizep = idx;
172 if (idx) {
173
174 return linebuf;
175 }
176 free(linebuf);
177 return NULL;
178}
179
180
181char* FAST_FUNC xmalloc_fgetline_fast(FILE *file)
182{
183 int sz;
184 char *r = xmalloc_fgets_internal(file, &sz);
185 if (r && r[sz - 1] == '\n')
186 r[--sz] = '\0';
187 return r;
188}
189
190char* FAST_FUNC xmalloc_fgets(FILE *file)
191{
192 int sz;
193 return xmalloc_fgets_internal(file, &sz);
194}
195
196
197char* FAST_FUNC xmalloc_fgetline(FILE *file)
198{
199 int sz;
200 char *r = xmalloc_fgets_internal(file, &sz);
201 if (!r)
202 return r;
203 if (r[sz - 1] == '\n')
204 r[--sz] = '\0';
205 return xrealloc(r, sz + 1);
206}
207#endif
208