get_line_from_file.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 <stdio.h>
  12. #include <stdlib.h>
  13. #include "libbb.h"
  14. /* get_line_from_file() - This function reads an entire line from a text file,
  15. * up to a newline or NUL byte. It returns a malloc'ed char * which must be
  16. * stored and free'ed by the caller. If end is null '\n' isn't considered
  17. * and of line. If end isn't null, length of the chunk read is stored in it. */
  18. char *bb_get_chunk_from_file(FILE * file, int *end)
  19. {
  20. int ch;
  21. int idx = 0;
  22. char *linebuf = NULL;
  23. int linebufsz = 0;
  24. while ((ch = getc(file)) != EOF) {
  25. /* grow the line buffer as necessary */
  26. if (idx > linebufsz - 2) {
  27. linebuf = xrealloc(linebuf, linebufsz += 80);
  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. if (ferror(file)) {
  37. free(linebuf);
  38. return NULL;
  39. }
  40. linebuf[idx] = 0;
  41. }
  42. return linebuf;
  43. }
  44. /* Get line, including trailing /n if any */
  45. char *bb_get_line_from_file(FILE * file)
  46. {
  47. int i;
  48. return bb_get_chunk_from_file(file, &i);
  49. }
  50. /* Get line. Remove trailing /n */
  51. char *bb_get_chomped_line_from_file(FILE * file)
  52. {
  53. int i;
  54. char *c = bb_get_chunk_from_file(file, &i);
  55. if (i && c[--i] == '\n')
  56. c[i] = 0;
  57. return c;
  58. }