getdelim.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 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 || *linebuf == NULL || *linebufsz == 0)
  40. && !(*linebuf == NULL && *linebufsz ==0 )) {
  41. errno=EINVAL;
  42. return -1;
  43. }
  44. if (*linebuf == NULL && *linebufsz == 0){
  45. *linebuf = malloc(GROWBY);
  46. if (!*linebuf) {
  47. errno=ENOMEM;
  48. return -1;
  49. }
  50. *linebufsz += GROWBY;
  51. }
  52. while (1) {
  53. ch = fgetc(file);
  54. if (ch == EOF)
  55. break;
  56. /* grow the line buffer as necessary */
  57. while (idx > *linebufsz-2) {
  58. *linebuf = realloc(*linebuf, *linebufsz += GROWBY);
  59. if (!*linebuf) {
  60. errno=ENOMEM;
  61. return -1;
  62. }
  63. }
  64. (*linebuf)[idx++] = (char)ch;
  65. if ((char)ch == delimiter)
  66. break;
  67. }
  68. if (idx != 0)
  69. (*linebuf)[idx] = 0;
  70. else if ( ch == EOF )
  71. return -1;
  72. return idx;
  73. }