getline.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /* getline.c -- Replacement for GNU C library function getline
  3. *
  4. * Copyright (C) 1993, 1996, 2001, 2002 Free Software Foundation, Inc.
  5. */
  6. /* Written by Jan Brittenson, bson@gnu.ai.mit.edu. */
  7. #include <assert.h>
  8. #include <stdio.h>
  9. /* Always add at least this many bytes when extending the buffer. */
  10. #define MIN_CHUNK 64
  11. /* Read up to (and including) a TERMINATOR from STREAM into *LINEPTR
  12. + OFFSET (and null-terminate it). *LINEPTR is a pointer returned from
  13. malloc (or NULL), pointing to *N characters of space. It is realloc'd
  14. as necessary. Return the number of characters read (not including the
  15. null terminator), or -1 on error or EOF.
  16. NOTE: There is another getstr() function declared in <curses.h>. */
  17. static int getstr(char **lineptr, size_t *n, FILE *stream,
  18. char terminator, size_t offset)
  19. {
  20. int nchars_avail; /* Allocated but unused chars in *LINEPTR. */
  21. char *read_pos; /* Where we're reading into *LINEPTR. */
  22. int ret;
  23. if (!lineptr || !n || !stream)
  24. return -1;
  25. if (!*lineptr) {
  26. *n = MIN_CHUNK;
  27. *lineptr = malloc(*n);
  28. if (!*lineptr)
  29. return -1;
  30. }
  31. nchars_avail = *n - offset;
  32. read_pos = *lineptr + offset;
  33. for (;;) {
  34. register int c = getc(stream);
  35. /* We always want at least one char left in the buffer, since we
  36. always (unless we get an error while reading the first char)
  37. NUL-terminate the line buffer. */
  38. assert(*n - nchars_avail == read_pos - *lineptr);
  39. if (nchars_avail < 2) {
  40. if (*n > MIN_CHUNK)
  41. *n *= 2;
  42. else
  43. *n += MIN_CHUNK;
  44. nchars_avail = *n + *lineptr - read_pos;
  45. *lineptr = realloc(*lineptr, *n);
  46. if (!*lineptr)
  47. return -1;
  48. read_pos = *n - nchars_avail + *lineptr;
  49. assert(*n - nchars_avail == read_pos - *lineptr);
  50. }
  51. if (c == EOF || ferror (stream)) {
  52. /* Return partial line, if any. */
  53. if (read_pos == *lineptr)
  54. return -1;
  55. else
  56. break;
  57. }
  58. *read_pos++ = c;
  59. nchars_avail--;
  60. if (c == terminator)
  61. /* Return the line. */
  62. break;
  63. }
  64. /* Done - NUL terminate and return the number of chars read. */
  65. *read_pos = '\0';
  66. ret = read_pos - (*lineptr + offset);
  67. return ret;
  68. }
  69. int getline (char **lineptr, size_t *n, FILE *stream)
  70. {
  71. return getstr(lineptr, n, stream, '\n', 0);
  72. }