getline.h 823 B

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