3
0

fgets_str.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 tarball for details.
  9. */
  10. #include "libbb.h"
  11. /* Read up to (and including) TERMINATING_STRING from FILE and return it.
  12. * Return NULL on EOF. */
  13. char *xmalloc_fgets_str(FILE *file, const char *terminating_string)
  14. {
  15. char *linebuf = NULL;
  16. const int term_length = strlen(terminating_string);
  17. int end_string_offset;
  18. int linebufsz = 0;
  19. int idx = 0;
  20. int ch;
  21. while (1) {
  22. ch = fgetc(file);
  23. if (ch == EOF) {
  24. free(linebuf);
  25. return NULL;
  26. }
  27. /* grow the line buffer as necessary */
  28. while (idx > linebufsz - 2) {
  29. linebufsz += 200;
  30. linebuf = xrealloc(linebuf, linebufsz);
  31. }
  32. linebuf[idx] = ch;
  33. idx++;
  34. /* Check for terminating string */
  35. end_string_offset = idx - term_length;
  36. if (end_string_offset > 0
  37. && memcmp(&linebuf[end_string_offset], terminating_string, term_length) == 0
  38. ) {
  39. idx -= term_length;
  40. break;
  41. }
  42. }
  43. linebuf = xrealloc(linebuf, idx + 1);
  44. linebuf[idx] = '\0';
  45. return linebuf;
  46. }