getdelim.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. #ifndef BUFSIZ
  32. #define BUFSIZ 512
  33. #endif
  34. ssize_t
  35. compat_getdelim_(char **buf, size_t *bufsiz, int delimiter, FILE *fp)
  36. {
  37. char *ptr, *eptr;
  38. if (*buf == NULL || *bufsiz == 0) {
  39. *bufsiz = BUFSIZ;
  40. if ((*buf = raw_malloc(*bufsiz)) == NULL)
  41. return -1;
  42. }
  43. for (ptr = *buf, eptr = *buf + *bufsiz;;) {
  44. int c = fgetc(fp);
  45. if (c == -1) {
  46. if (feof(fp)) {
  47. ssize_t diff = (ssize_t)(ptr - *buf);
  48. if (diff != 0) {
  49. *ptr = '\0';
  50. return diff;
  51. }
  52. }
  53. return -1;
  54. }
  55. *ptr++ = c;
  56. if (c == delimiter) {
  57. *ptr = '\0';
  58. return ptr - *buf;
  59. }
  60. if (ptr + 2 >= eptr) {
  61. char *nbuf;
  62. size_t nbufsiz = *bufsiz * 2;
  63. ssize_t d = ptr - *buf;
  64. if ((nbuf = raw_realloc(*buf, nbufsiz)) == NULL)
  65. return -1;
  66. *buf = nbuf;
  67. *bufsiz = nbufsiz;
  68. eptr = nbuf + nbufsiz;
  69. ptr = nbuf + d;
  70. }
  71. }
  72. }