getline.h 811 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Simple POSIX getline() implementation
  2. // This code is public domain
  3. #include "malloc.h"
  4. #include "stdio.h"
  5. ssize_t getline(char **lineptr, size_t *n, FILE *stream) {
  6. if (!lineptr || !stream || !n)
  7. return -1;
  8. int c = getc(stream);
  9. if (c == EOF)
  10. return -1;
  11. if (!*lineptr) {
  12. *lineptr = malloc(128);
  13. if (!*lineptr)
  14. return -1;
  15. *n = 128;
  16. }
  17. size_t pos = 0;
  18. while(c != EOF) {
  19. if (pos + 1 >= *n) {
  20. size_t new_size = *n + (*n >> 2);
  21. if (new_size < 128)
  22. new_size = 128;
  23. char *new_ptr = realloc(*lineptr, new_size);
  24. if (!new_ptr)
  25. return -1;
  26. *n = new_size;
  27. *lineptr = new_ptr;
  28. }
  29. ((unsigned char *)(*lineptr))[pos ++] = c;
  30. if (c == '\n')
  31. break;
  32. c = getc(stream);
  33. }
  34. (*lineptr)[pos] = '\0';
  35. return pos;
  36. }