fgets_str.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright (C) many different people.
  6. * If you wrote this, please acknowledge your work.
  7. *
  8. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  9. */
  10. #include "libbb.h"
  11. static char *xmalloc_fgets_internal(FILE *file, const char *terminating_string, int chop_off, size_t *maxsz_p)
  12. {
  13. char *linebuf = NULL;
  14. const int term_length = strlen(terminating_string);
  15. int end_string_offset;
  16. int linebufsz = 0;
  17. int idx = 0;
  18. int ch;
  19. size_t maxsz = maxsz_p ? *maxsz_p : INT_MAX - 4095;
  20. while (1) {
  21. ch = fgetc(file);
  22. if (ch == EOF) {
  23. if (idx == 0)
  24. return linebuf; /* NULL */
  25. break;
  26. }
  27. if (idx >= linebufsz) {
  28. linebufsz += 200;
  29. linebuf = xrealloc(linebuf, linebufsz);
  30. if (idx >= maxsz) {
  31. linebuf[idx] = ch;
  32. idx++;
  33. break;
  34. }
  35. }
  36. linebuf[idx] = ch;
  37. idx++;
  38. /* Check for terminating string */
  39. end_string_offset = idx - term_length;
  40. if (end_string_offset >= 0
  41. && memcmp(&linebuf[end_string_offset], terminating_string, term_length) == 0
  42. ) {
  43. if (chop_off)
  44. idx -= term_length;
  45. break;
  46. }
  47. }
  48. /* Grow/shrink *first*, then store NUL */
  49. linebuf = xrealloc(linebuf, idx + 1);
  50. linebuf[idx] = '\0';
  51. if (maxsz_p)
  52. *maxsz_p = idx;
  53. return linebuf;
  54. }
  55. /* Read up to TERMINATING_STRING from FILE and return it,
  56. * including terminating string.
  57. * Non-terminated string can be returned if EOF is reached.
  58. * Return NULL if EOF is reached immediately. */
  59. char* FAST_FUNC xmalloc_fgets_str(FILE *file, const char *terminating_string)
  60. {
  61. return xmalloc_fgets_internal(file, terminating_string, 0, NULL);
  62. }
  63. char* FAST_FUNC xmalloc_fgets_str_len(FILE *file, const char *terminating_string, size_t *maxsz_p)
  64. {
  65. return xmalloc_fgets_internal(file, terminating_string, 0, maxsz_p);
  66. }
  67. char* FAST_FUNC xmalloc_fgetline_str(FILE *file, const char *terminating_string)
  68. {
  69. return xmalloc_fgets_internal(file, terminating_string, 1, NULL);
  70. }