xs_io.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* copyright (c) 2022 - 2024 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. s = xs_append_m(s, (char *)&rc, 1);
  20. if (c == '\n')
  21. break;
  22. }
  23. }
  24. return s;
  25. }
  26. xs_val *xs_read(FILE *f, int *sz)
  27. /* reads up to size bytes from f */
  28. {
  29. xs_val *s = NULL;
  30. int size = *sz;
  31. int rdsz = 0;
  32. errno = 0;
  33. while (size > 0 && !feof(f)) {
  34. char tmp[4096];
  35. int n, r;
  36. if ((n = sizeof(tmp)) > size)
  37. n = size;
  38. r = fread(tmp, 1, n, f);
  39. /* open room */
  40. s = xs_realloc(s, rdsz + r);
  41. /* copy read data */
  42. memcpy(s + rdsz, tmp, r);
  43. rdsz += r;
  44. size -= r;
  45. }
  46. /* null terminate, just in case it's treated as a string */
  47. s = xs_realloc(s, _xs_blk_size(rdsz + 1));
  48. s[rdsz] = '\0';
  49. *sz = rdsz;
  50. return s;
  51. }
  52. xs_val *xs_readall(FILE *f)
  53. /* reads the rest of the file into a string */
  54. {
  55. int size = XS_ALL;
  56. return xs_read(f, &size);
  57. }
  58. #endif /* XS_IMPLEMENTATION */
  59. #endif /* _XS_IO_H */