10 |
|
|
11 |
#include "libbb.h" |
#include "libbb.h" |
12 |
|
|
13 |
static char *xmalloc_fgets_internal(FILE *file, const char *terminating_string, int chop_off) |
static char *xmalloc_fgets_internal(FILE *file, const char *terminating_string, int chop_off, size_t *maxsz_p) |
14 |
{ |
{ |
15 |
char *linebuf = NULL; |
char *linebuf = NULL; |
16 |
const int term_length = strlen(terminating_string); |
const int term_length = strlen(terminating_string); |
18 |
int linebufsz = 0; |
int linebufsz = 0; |
19 |
int idx = 0; |
int idx = 0; |
20 |
int ch; |
int ch; |
21 |
|
size_t maxsz = *maxsz_p; |
22 |
|
|
23 |
while (1) { |
while (1) { |
24 |
ch = fgetc(file); |
ch = fgetc(file); |
31 |
if (idx >= linebufsz) { |
if (idx >= linebufsz) { |
32 |
linebufsz += 200; |
linebufsz += 200; |
33 |
linebuf = xrealloc(linebuf, linebufsz); |
linebuf = xrealloc(linebuf, linebufsz); |
34 |
|
if (idx >= maxsz) { |
35 |
|
linebuf[idx] = ch; |
36 |
|
idx++; |
37 |
|
break; |
38 |
|
} |
39 |
} |
} |
40 |
|
|
41 |
linebuf[idx] = ch; |
linebuf[idx] = ch; |
54 |
/* Grow/shrink *first*, then store NUL */ |
/* Grow/shrink *first*, then store NUL */ |
55 |
linebuf = xrealloc(linebuf, idx + 1); |
linebuf = xrealloc(linebuf, idx + 1); |
56 |
linebuf[idx] = '\0'; |
linebuf[idx] = '\0'; |
57 |
|
*maxsz_p = idx; |
58 |
return linebuf; |
return linebuf; |
59 |
} |
} |
60 |
|
|
64 |
* Return NULL if EOF is reached immediately. */ |
* Return NULL if EOF is reached immediately. */ |
65 |
char* FAST_FUNC xmalloc_fgets_str(FILE *file, const char *terminating_string) |
char* FAST_FUNC xmalloc_fgets_str(FILE *file, const char *terminating_string) |
66 |
{ |
{ |
67 |
return xmalloc_fgets_internal(file, terminating_string, 0); |
size_t maxsz = INT_MAX - 4095; |
68 |
|
return xmalloc_fgets_internal(file, terminating_string, 0, &maxsz); |
69 |
|
} |
70 |
|
|
71 |
|
char* FAST_FUNC xmalloc_fgets_str_len(FILE *file, const char *terminating_string, size_t *maxsz_p) |
72 |
|
{ |
73 |
|
size_t maxsz; |
74 |
|
|
75 |
|
if (!maxsz_p) { |
76 |
|
maxsz = INT_MAX - 4095; |
77 |
|
maxsz_p = &maxsz; |
78 |
|
} |
79 |
|
return xmalloc_fgets_internal(file, terminating_string, 0, maxsz_p); |
80 |
} |
} |
81 |
|
|
82 |
char* FAST_FUNC xmalloc_fgetline_str(FILE *file, const char *terminating_string) |
char* FAST_FUNC xmalloc_fgetline_str(FILE *file, const char *terminating_string) |
83 |
{ |
{ |
84 |
return xmalloc_fgets_internal(file, terminating_string, 1); |
size_t maxsz = INT_MAX - 4095; |
85 |
|
return xmalloc_fgets_internal(file, terminating_string, 1, &maxsz); |
86 |
} |
} |