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