getdelim.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * getdelim for uclibc
  4. *
  5. * Copyright (C) 2000 by Lineo, inc. Written by Erik Andersen
  6. * <andersen@lineo.com>, <andersee@debian.org>
  7. *
  8. * This program is free software; you can redistribute it and/or modify it
  9. * under the terms of the GNU Library General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or (at your
  11. * option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful, but WITHOUT
  14. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  15. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  16. * more details.
  17. *
  18. * You should have received a copy of the GNU Library General Public License
  19. * along with this program; if not, write to the Free Software Foundation,
  20. * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  21. *
  22. */
  23. #include <stddef.h>
  24. #include <stdio.h>
  25. #include <stdlib.h>
  26. #include <string.h>
  27. #include <limits.h>
  28. #include <errno.h>
  29. /* Read up to (and including) a TERMINATOR from STREAM into *LINEPTR
  30. (and null-terminate it). *LINEPTR is a pointer returned from malloc (or
  31. NULL), pointing to *N characters of space. It is realloc'd as
  32. necessary. Returns the number of characters read (not including the
  33. null delimiter), or -1 on error or EOF. */
  34. size_t getdelim(char **linebuf, size_t *linebufsz, int delimiter, FILE *file)
  35. {
  36. static const int GROWBY = 80; /* how large we will grow strings by */
  37. int ch;
  38. int idx = 0;
  39. if (file == NULL || linebuf==NULL || *linebuf == NULL || linebufsz == NULL) {
  40. errno=EINVAL;
  41. return -1;
  42. }
  43. while (1) {
  44. ch = fgetc(file);
  45. if (ch == EOF)
  46. break;
  47. /* grow the line buffer as necessary */
  48. while (idx > *linebufsz-2) {
  49. *linebuf = realloc(*linebuf, *linebufsz += GROWBY);
  50. if (!*linebuf) {
  51. errno=ENOMEM;
  52. return -1;
  53. }
  54. }
  55. (*linebuf)[idx++] = (char)ch;
  56. if ((char)ch == delimiter)
  57. break;
  58. }
  59. if (idx != 0)
  60. (*linebuf)[idx] = 0;
  61. return idx;
  62. }