Changeset 2725 in MondoRescue for branches/2.2.9/mindi-busybox/libbb/fgets_str.c
- Timestamp:
- Feb 25, 2011, 9:26:54 PM (13 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/2.2.9/mindi-busybox/libbb/fgets_str.c
r1765 r2725 6 6 * If you wrote this, please acknowledge your work. 7 7 * 8 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.8 * Licensed under GPLv2 or later, see file LICENSE in this source tree. 9 9 */ 10 10 11 11 #include "libbb.h" 12 12 13 /* Read up to (and including) TERMINATING_STRING from FILE and return it. 14 * Return NULL on EOF. */ 15 16 char *xmalloc_fgets_str(FILE *file, const char *terminating_string) 13 static char *xmalloc_fgets_internal(FILE *file, const char *terminating_string, int chop_off, size_t *maxsz_p) 17 14 { 18 15 char *linebuf = NULL; … … 22 19 int idx = 0; 23 20 int ch; 21 size_t maxsz = *maxsz_p; 24 22 25 23 while (1) { 26 24 ch = fgetc(file); 27 25 if (ch == EOF) { 28 free(linebuf); 29 return NULL; 26 if (idx == 0) 27 return linebuf; /* NULL */ 28 break; 30 29 } 31 30 32 /* grow the line buffer as necessary */ 33 while (idx > linebufsz - 2) { 31 if (idx >= linebufsz) { 34 32 linebufsz += 200; 35 33 linebuf = xrealloc(linebuf, linebufsz); 34 if (idx >= maxsz) { 35 linebuf[idx] = ch; 36 idx++; 37 break; 38 } 36 39 } 37 40 … … 41 44 /* Check for terminating string */ 42 45 end_string_offset = idx - term_length; 43 if (end_string_offset > 046 if (end_string_offset >= 0 44 47 && memcmp(&linebuf[end_string_offset], terminating_string, term_length) == 0 45 48 ) { 46 idx -= term_length; 49 if (chop_off) 50 idx -= term_length; 47 51 break; 48 52 } 49 53 } 54 /* Grow/shrink *first*, then store NUL */ 50 55 linebuf = xrealloc(linebuf, idx + 1); 51 56 linebuf[idx] = '\0'; 57 *maxsz_p = idx; 52 58 return linebuf; 53 59 } 60 61 /* Read up to TERMINATING_STRING from FILE and return it, 62 * including terminating string. 63 * Non-terminated string can be returned if EOF is reached. 64 * Return NULL if EOF is reached immediately. */ 65 char* FAST_FUNC xmalloc_fgets_str(FILE *file, const char *terminating_string) 66 { 67 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) 83 { 84 size_t maxsz = INT_MAX - 4095; 85 return xmalloc_fgets_internal(file, terminating_string, 1, &maxsz); 86 }
Note:
See TracChangeset
for help on using the changeset viewer.