snac2/xs_io.h

91 lines
1.5 KiB
C
Raw Normal View History

2024-01-04 11:22:03 +03:00
/* copyright (c) 2022 - 2024 grunfink et al. / MIT license */
2022-09-19 21:41:11 +03:00
#ifndef _XS_IO_H
#define _XS_IO_H
2023-01-28 19:49:02 +03:00
xs_str *xs_readline(FILE *f);
xs_val *xs_read(FILE *f, int *size);
xs_val *xs_readall(FILE *f);
2022-09-19 21:41:11 +03:00
#ifdef XS_IMPLEMENTATION
2023-01-28 19:49:02 +03:00
xs_str *xs_readline(FILE *f)
2022-09-19 21:41:11 +03:00
/* reads a line from a file */
{
2023-01-28 19:49:02 +03:00
xs_str *s = NULL;
2022-09-19 21:41:11 +03:00
errno = 0;
/* don't even try on eof */
if (!feof(f)) {
int c;
s = xs_str_new(NULL);
while ((c = fgetc(f)) != EOF) {
unsigned char rc = c;
s = xs_append_m(s, (char *)&rc, 1);
if (c == '\n')
break;
}
}
return s;
}
2023-01-28 19:49:02 +03:00
xs_val *xs_read(FILE *f, int *sz)
2022-09-19 21:41:11 +03:00
/* reads up to size bytes from f */
{
2023-01-28 19:49:02 +03:00
xs_val *s = NULL;
int size = *sz;
int rdsz = 0;
2022-09-19 21:41:11 +03:00
errno = 0;
2022-09-28 10:29:09 +03:00
while (size > 0 && !feof(f)) {
char tmp[4096];
2022-09-19 21:41:11 +03:00
int n, r;
if ((n = sizeof(tmp)) > size)
n = size;
r = fread(tmp, 1, n, f);
/* open room */
s = xs_realloc(s, rdsz + r);
/* copy read data */
memcpy(s + rdsz, tmp, r);
2022-09-28 10:29:09 +03:00
rdsz += r;
size -= r;
2022-09-19 21:41:11 +03:00
}
2022-10-16 20:58:59 +03:00
/* null terminate, just in case it's treated as a string */
2022-12-09 20:43:31 +03:00
s = xs_realloc(s, _xs_blk_size(rdsz + 1));
2022-10-16 20:58:59 +03:00
s[rdsz] = '\0';
2022-09-28 10:29:09 +03:00
*sz = rdsz;
2022-09-19 21:41:11 +03:00
return s;
}
2022-10-17 21:32:47 +03:00
2023-01-28 19:49:02 +03:00
xs_val *xs_readall(FILE *f)
2022-10-17 21:32:47 +03:00
/* reads the rest of the file into a string */
{
2022-11-24 10:47:02 +03:00
int size = XS_ALL;
2022-10-17 21:32:47 +03:00
return xs_read(f, &size);
}
2022-09-19 21:41:11 +03:00
#endif /* XS_IMPLEMENTATION */
#endif /* _XS_IO_H */