get_line_from_file.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. linebufsz += 80;
  27. linebuf = xrealloc(linebuf, linebufsz);
  28. }
  29. linebuf[idx++] = (char) ch;
  30. if (!ch || (end && ch == '\n'))
  31. break;
  32. }
  33. if (end)
  34. *end = idx;
  35. if (linebuf) {
  36. // huh, does fgets discard prior data on error like this?
  37. // I don't think so....
  38. //if (ferror(file)) {
  39. // free(linebuf);
  40. // return NULL;
  41. //}
  42. linebuf = xrealloc(linebuf, idx+1);
  43. linebuf[idx] = '\0';
  44. }
  45. return linebuf;
  46. }
  47. /* Get line, including trailing \n if any */
  48. char *xmalloc_fgets(FILE *file)
  49. {
  50. int i;
  51. return bb_get_chunk_from_file(file, &i);
  52. }
  53. /* Get line. Remove trailing \n */
  54. char *xmalloc_getline(FILE *file)
  55. {
  56. int i;
  57. char *c = bb_get_chunk_from_file(file, &i);
  58. if (i && c[--i] == '\n')
  59. c[i] = '\0';
  60. return c;
  61. }