summaryrefslogtreecommitdiff
path: root/xs_io.h
diff options
context:
space:
mode:
authordefault <nobody@localhost>2022-09-19 20:41:11 +0200
committerdefault <nobody@localhost>2022-09-19 20:41:11 +0200
commit67288a763b8bceadbb128d2cf5bdc431ba8a686f (patch)
tree0a0bc1922016bbd3d3cd2ec3c80a033970280a9f /xs_io.h
parentef03035ef0af5a68ba7e03ae834a43db5dd3a8e3 (diff)
Imported xs.
Diffstat (limited to 'xs_io.h')
-rw-r--r--xs_io.h86
1 files changed, 86 insertions, 0 deletions
diff --git a/xs_io.h b/xs_io.h
new file mode 100644
index 0000000..523d207
--- /dev/null
+++ b/xs_io.h
@@ -0,0 +1,86 @@
+/* copyright (c) 2022 grunfink - MIT license */
+
+#ifndef _XS_IO_H
+
+#define _XS_IO_H
+
+d_char *xs_readall(FILE *f);
+d_char *xs_readline(FILE *f);
+d_char *xs_read(FILE *f, int size);
+
+
+#ifdef XS_IMPLEMENTATION
+
+d_char *xs_readall(FILE *f)
+/* reads the rest of the file into a string */
+{
+ d_char *s;
+ char tmp[1024];
+
+ errno = 0;
+
+ /* create the new string */
+ s = xs_str_new(NULL);
+
+ while (fgets(tmp, sizeof(tmp), f))
+ s = xs_str_cat(s, tmp);
+
+ return s;
+}
+
+
+d_char *xs_readline(FILE *f)
+/* reads a line from a file */
+{
+ d_char *s = NULL;
+
+ 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;
+}
+
+
+d_char *xs_read(FILE *f, int size)
+/* reads up to size bytes from f */
+{
+ d_char *s;
+
+ errno = 0;
+
+ s = xs_str_new(NULL);
+
+ while (size != 0 && !feof(f)) {
+ char tmp[2048];
+ int n, r;
+
+ if ((n = sizeof(tmp)) > size)
+ n = size;
+
+ r = fread(tmp, 1, n, f);
+ s = xs_append_m(s, tmp, r);
+
+ size -= r;
+ }
+
+ return s;
+}
+
+#endif /* XS_IMPLEMENTATION */
+
+#endif /* _XS_IO_H */