get_line_from_file.c 1.5 KB

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