xs_io.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* copyright (c) 2022 - 2025 grunfink et al. / MIT license */
  2. #ifndef _XS_IO_H
  3. #define _XS_IO_H
  4. xs_str *xs_readline(FILE *f);
  5. xs_val *xs_read(FILE *f, int *size);
  6. xs_val *xs_readall(FILE *f);
  7. #ifdef XS_IMPLEMENTATION
  8. xs_str *xs_readline(FILE *f)
  9. /* reads a line from a file */
  10. {
  11. xs_str *s = NULL;
  12. errno = 0;
  13. /* don't even try on eof */
  14. if (!feof(f)) {
  15. int c;
  16. s = xs_str_new(NULL);
  17. while ((c = fgetc(f)) != EOF) {
  18. unsigned char rc = c;
  19. if (xs_is_string((char *)&rc))
  20. s = xs_append_m(s, (char *)&rc, 1);
  21. if (c == '\n')
  22. break;
  23. }
  24. }
  25. return s;
  26. }
  27. xs_val *xs_read(FILE *f, int *sz)
  28. /* reads up to size bytes from f */
  29. {
  30. xs_val *s = NULL;
  31. int size = *sz;
  32. int rdsz = 0;
  33. errno = 0;
  34. while (size > 0 && !feof(f)) {
  35. char tmp[4096];
  36. int n, r;
  37. if ((n = sizeof(tmp)) > size)
  38. n = size;
  39. r = fread(tmp, 1, n, f);
  40. /* open room */
  41. s = xs_realloc(s, rdsz + r);
  42. /* copy read data */
  43. memcpy(s + rdsz, tmp, r);
  44. rdsz += r;
  45. size -= r;
  46. }
  47. /* null terminate, just in case it's treated as a string */
  48. s = xs_realloc(s, _xs_blk_size(rdsz + 1));
  49. s[rdsz] = '\0';
  50. *sz = rdsz;
  51. return s;
  52. }
  53. xs_val *xs_readall(FILE *f)
  54. /* reads the rest of the file into a string */
  55. {
  56. int size = XS_ALL;
  57. return xs_read(f, &size);
  58. }
  59. #endif /* XS_IMPLEMENTATION */
  60. #endif /* _XS_IO_H */