| 1 | // Aseprite |
| 2 | // Copyright (C) 2001-2015 David Capello |
| 3 | // |
| 4 | // This program is distributed under the terms of |
| 5 | // the End-User License Agreement for Aseprite. |
| 6 | |
| 7 | #ifdef HAVE_CONFIG_H |
| 8 | #include "config.h" |
| 9 | #endif |
| 10 | |
| 11 | #include <cstring> |
| 12 | #include <cstdio> |
| 13 | |
| 14 | static int line_num; |
| 15 | |
| 16 | static char* tok_fgets(char* buf, int size, FILE* file); |
| 17 | |
| 18 | void tok_reset_line_num() |
| 19 | { |
| 20 | line_num = 0; |
| 21 | } |
| 22 | |
| 23 | int tok_line_num() |
| 24 | { |
| 25 | return line_num; |
| 26 | } |
| 27 | |
| 28 | char* tok_read(FILE* f, char* buf, char* leavings, int sizeof_leavings) |
| 29 | { |
| 30 | int ch, len = 0; |
| 31 | char* s; |
| 32 | |
| 33 | *buf = 0; |
| 34 | |
| 35 | if (feof(f)) |
| 36 | return NULL; |
| 37 | |
| 38 | while (!*buf) { |
| 39 | if (!*leavings) { |
| 40 | line_num++; |
| 41 | if (!tok_fgets(leavings, sizeof_leavings, f)) |
| 42 | return NULL; |
| 43 | } |
| 44 | |
| 45 | s = leavings; |
| 46 | |
| 47 | for (ch=*s; ch; ch=*s) { |
| 48 | if (ch == ' ') { |
| 49 | s++; |
| 50 | } |
| 51 | else if (ch == '#') { |
| 52 | s += strlen(s); |
| 53 | break; |
| 54 | } |
| 55 | else if (ch == '\"') { |
| 56 | s++; |
| 57 | |
| 58 | for (ch=*s; ; ch=*s) { |
| 59 | if (!ch) { |
| 60 | line_num++; |
| 61 | if (!tok_fgets(leavings, sizeof_leavings, f)) |
| 62 | break; |
| 63 | else { |
| 64 | s = leavings; |
| 65 | continue; |
| 66 | } |
| 67 | } |
| 68 | else if (ch == '\\') { |
| 69 | s++; |
| 70 | switch (*s) { |
| 71 | case 'n': ch = '\n'; break; |
| 72 | default: ch = *s; break; |
| 73 | } |
| 74 | } |
| 75 | else if (ch == '\"') { |
| 76 | s++; |
| 77 | break; |
| 78 | } |
| 79 | buf[len++] = ch; |
| 80 | s++; |
| 81 | } |
| 82 | break; |
| 83 | } |
| 84 | else { |
| 85 | for (ch=*s; (ch) && (ch != ' '); ch=*s) { |
| 86 | buf[len++] = ch; |
| 87 | s++; |
| 88 | } |
| 89 | break; |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | memmove(leavings, s, strlen(s)+1); |
| 94 | } |
| 95 | |
| 96 | buf[len] = 0; |
| 97 | return buf; |
| 98 | } |
| 99 | |
| 100 | /* returns the readed line or NULL if EOF (the line will not have the |
| 101 | "\n" character) */ |
| 102 | static char* tok_fgets(char* buf, int size, FILE* file) |
| 103 | { |
| 104 | char* ret = fgets(buf, size, file); |
| 105 | |
| 106 | if (ret && *ret) { |
| 107 | // Remove trailing \r\n |
| 108 | char* s = ret + strlen(ret); |
| 109 | do { |
| 110 | *(s--) = 0; |
| 111 | } while (s >= ret && *s && (*s == '\n' || *s == '\r')); |
| 112 | } |
| 113 | |
| 114 | return ret; |
| 115 | } |
| 116 | |