fgetline.c 659 B

1234567891011121314151617181920212223242526
  1. /*
  2. * Read an entire line of text from a file. Return a buffer
  3. * malloced to be as big as necessary (caller must free).
  4. */
  5. #include "defs.h"
  6. #include "misc.h"
  7. char *fgetline(FILE *fp)
  8. {
  9. char *ret = snewn(512, char);
  10. size_t size = 512, len = 0;
  11. while (fgets(ret + len, size - len, fp)) {
  12. len += strlen(ret + len);
  13. if (len > 0 && ret[len-1] == '\n')
  14. break; /* got a newline, we're done */
  15. sgrowarrayn_nm(ret, size, len, 512);
  16. }
  17. if (len == 0) { /* first fgets returned NULL */
  18. sfree(ret);
  19. return NULL;
  20. }
  21. ret[len] = '\0';
  22. return ret;
  23. }