getdelim.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* vi: set sw=4 ts=4: */
  2. /* getdelim for uClibc
  3. *
  4. * Copyright (C) 2000 by Lineo, inc. and Erik Andersen
  5. * Copyright (C) 2000,2001 by Erik Andersen <andersen@uclibc.org>
  6. * Written by Erik Andersen <andersen@uclibc.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 Library General Public License
  16. * for 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. ssize_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 || linebufsz == NULL) {
  40. __set_errno(EINVAL);
  41. return -1;
  42. }
  43. if (*linebuf == NULL || *linebufsz < 2) {
  44. *linebuf = malloc(GROWBY);
  45. if (!*linebuf) {
  46. __set_errno(ENOMEM);
  47. return -1;
  48. }
  49. *linebufsz += GROWBY;
  50. }
  51. while (1) {
  52. ch = fgetc(file);
  53. if (ch == EOF)
  54. break;
  55. /* grow the line buffer as necessary */
  56. while (idx > *linebufsz-2) {
  57. *linebuf = realloc(*linebuf, *linebufsz += GROWBY);
  58. if (!*linebuf) {
  59. __set_errno(ENOMEM);
  60. return -1;
  61. }
  62. }
  63. (*linebuf)[idx++] = (char)ch;
  64. if ((char)ch == delimiter)
  65. break;
  66. }
  67. if (idx != 0)
  68. (*linebuf)[idx] = 0;
  69. else if ( ch == EOF )
  70. return -1;
  71. return idx;
  72. }