getdelim.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* $NetBSD: getdelim.c,v 1.2 2015/12/25 20:12:46 joerg Exp $ */
  2. /* NetBSD-src: getline.c,v 1.2 2014/09/16 17:23:50 christos Exp */
  3. /*-
  4. * Copyright (c) 2011 The NetBSD Foundation, Inc.
  5. * All rights reserved.
  6. *
  7. * This code is derived from software contributed to The NetBSD Foundation
  8. * by Christos Zoulas.
  9. *
  10. * Redistribution and use in source and binary forms, with or without
  11. * modification, are permitted provided that the following conditions
  12. * are met:
  13. * 1. Redistributions of source code must retain the above copyright
  14. * notice, this list of conditions and the following disclaimer.
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in the
  17. * documentation and/or other materials provided with the distribution.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
  20. * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  21. * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  22. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
  23. * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  24. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  25. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  26. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  27. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  28. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  29. * POSSIBILITY OF SUCH DAMAGE.
  30. */
  31. #include <nbcompat.h>
  32. #include <nbcompat/stdio.h>
  33. #include <nbcompat/stdlib.h>
  34. #if !HAVE_GETDELIM
  35. ssize_t
  36. getdelim(char **buf, size_t *bufsiz, int delimiter, FILE *fp)
  37. {
  38. char *ptr, *eptr;
  39. if (*buf == NULL || *bufsiz == 0) {
  40. *bufsiz = BUFSIZ;
  41. if ((*buf = malloc(*bufsiz)) == NULL)
  42. return -1;
  43. }
  44. for (ptr = *buf, eptr = *buf + *bufsiz;;) {
  45. int c = fgetc(fp);
  46. if (c == -1) {
  47. if (feof(fp)) {
  48. ssize_t diff = (ssize_t)(ptr - *buf);
  49. if (diff != 0) {
  50. *ptr = '\0';
  51. return diff;
  52. }
  53. }
  54. return -1;
  55. }
  56. *ptr++ = c;
  57. if (c == delimiter) {
  58. *ptr = '\0';
  59. return ptr - *buf;
  60. }
  61. if (ptr + 2 >= eptr) {
  62. char *nbuf;
  63. size_t nbufsiz = *bufsiz * 2;
  64. ssize_t d = ptr - *buf;
  65. if ((nbuf = realloc(*buf, nbufsiz)) == NULL)
  66. return -1;
  67. *buf = nbuf;
  68. *bufsiz = nbufsiz;
  69. eptr = nbuf + nbufsiz;
  70. ptr = nbuf + d;
  71. }
  72. }
  73. }
  74. #endif