get_line_from_file.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright (C) 2005, 2006 Rob Landley <rob@landley.net>
  6. * Copyright (C) 2004 Erik Andersen <andersen@codepoet.org>
  7. * Copyright (C) 2001 Matt Krai
  8. *
  9. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  10. */
  11. #include "libbb.h"
  12. /* This function reads an entire line from a text file, up to a newline
  13. * or NUL byte, inclusive. It returns a malloc'ed char * which must be
  14. * stored and free'ed by the caller. If end is NULL '\n' isn't considered
  15. * end of line. If end isn't NULL, length of the chunk read is stored in it.
  16. * Return NULL if EOF/error */
  17. char *bb_get_chunk_from_file(FILE * file, int *end)
  18. {
  19. int ch;
  20. int idx = 0;
  21. char *linebuf = NULL;
  22. int linebufsz = 0;
  23. while ((ch = getc(file)) != EOF) {
  24. /* grow the line buffer as necessary */
  25. if (idx >= linebufsz) {
  26. linebuf = xrealloc(linebuf, linebufsz += 80);
  27. }
  28. linebuf[idx++] = (char) ch;
  29. if (!ch || (end && ch == '\n'))
  30. break;
  31. }
  32. if (end)
  33. *end = idx;
  34. if (linebuf) {
  35. // huh, does fgets discard prior data on error like this?
  36. // I don't think so....
  37. //if (ferror(file)) {
  38. // free(linebuf);
  39. // return NULL;
  40. //}
  41. linebuf = xrealloc(linebuf, idx+1);
  42. linebuf[idx] = '\0';
  43. }
  44. return linebuf;
  45. }
  46. /* Get line, including trailing \n if any */
  47. char *xmalloc_fgets(FILE * file)
  48. {
  49. int i;
  50. return bb_get_chunk_from_file(file, &i);
  51. }
  52. /* Get line. Remove trailing \n */
  53. char *xmalloc_getline(FILE * file)
  54. {
  55. int i;
  56. char *c = bb_get_chunk_from_file(file, &i);
  57. if (i && c[--i] == '\n')
  58. c[i] = '\0';
  59. return c;
  60. }