diff options
| author | 2022-09-19 20:41:11 +0200 | |
|---|---|---|
| committer | 2022-09-19 20:41:11 +0200 | |
| commit | 67288a763b8bceadbb128d2cf5bdc431ba8a686f (patch) | |
| tree | 0a0bc1922016bbd3d3cd2ec3c80a033970280a9f /xs_io.h | |
| parent | Project started. (diff) | |
| download | penes-snac2-67288a763b8bceadbb128d2cf5bdc431ba8a686f.tar.gz penes-snac2-67288a763b8bceadbb128d2cf5bdc431ba8a686f.tar.xz penes-snac2-67288a763b8bceadbb128d2cf5bdc431ba8a686f.zip | |
Imported xs.
Diffstat (limited to 'xs_io.h')
| -rw-r--r-- | xs_io.h | 86 |
1 files changed, 86 insertions, 0 deletions
| @@ -0,0 +1,86 @@ | |||
| 1 | /* copyright (c) 2022 grunfink - MIT license */ | ||
| 2 | |||
| 3 | #ifndef _XS_IO_H | ||
| 4 | |||
| 5 | #define _XS_IO_H | ||
| 6 | |||
| 7 | d_char *xs_readall(FILE *f); | ||
| 8 | d_char *xs_readline(FILE *f); | ||
| 9 | d_char *xs_read(FILE *f, int size); | ||
| 10 | |||
| 11 | |||
| 12 | #ifdef XS_IMPLEMENTATION | ||
| 13 | |||
| 14 | d_char *xs_readall(FILE *f) | ||
| 15 | /* reads the rest of the file into a string */ | ||
| 16 | { | ||
| 17 | d_char *s; | ||
| 18 | char tmp[1024]; | ||
| 19 | |||
| 20 | errno = 0; | ||
| 21 | |||
| 22 | /* create the new string */ | ||
| 23 | s = xs_str_new(NULL); | ||
| 24 | |||
| 25 | while (fgets(tmp, sizeof(tmp), f)) | ||
| 26 | s = xs_str_cat(s, tmp); | ||
| 27 | |||
| 28 | return s; | ||
| 29 | } | ||
| 30 | |||
| 31 | |||
| 32 | d_char *xs_readline(FILE *f) | ||
| 33 | /* reads a line from a file */ | ||
| 34 | { | ||
| 35 | d_char *s = NULL; | ||
| 36 | |||
| 37 | errno = 0; | ||
| 38 | |||
| 39 | /* don't even try on eof */ | ||
| 40 | if (!feof(f)) { | ||
| 41 | int c; | ||
| 42 | |||
| 43 | s = xs_str_new(NULL); | ||
| 44 | |||
| 45 | while ((c = fgetc(f)) != EOF) { | ||
| 46 | unsigned char rc = c; | ||
| 47 | |||
| 48 | s = xs_append_m(s, (char *)&rc, 1); | ||
| 49 | |||
| 50 | if (c == '\n') | ||
| 51 | break; | ||
| 52 | } | ||
| 53 | } | ||
| 54 | |||
| 55 | return s; | ||
| 56 | } | ||
| 57 | |||
| 58 | |||
| 59 | d_char *xs_read(FILE *f, int size) | ||
| 60 | /* reads up to size bytes from f */ | ||
| 61 | { | ||
| 62 | d_char *s; | ||
| 63 | |||
| 64 | errno = 0; | ||
| 65 | |||
| 66 | s = xs_str_new(NULL); | ||
| 67 | |||
| 68 | while (size != 0 && !feof(f)) { | ||
| 69 | char tmp[2048]; | ||
| 70 | int n, r; | ||
| 71 | |||
| 72 | if ((n = sizeof(tmp)) > size) | ||
| 73 | n = size; | ||
| 74 | |||
| 75 | r = fread(tmp, 1, n, f); | ||
| 76 | s = xs_append_m(s, tmp, r); | ||
| 77 | |||
| 78 | size -= r; | ||
| 79 | } | ||
| 80 | |||
| 81 | return s; | ||
| 82 | } | ||
| 83 | |||
| 84 | #endif /* XS_IMPLEMENTATION */ | ||
| 85 | |||
| 86 | #endif /* _XS_IO_H */ | ||