-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsfile.h
125 lines (114 loc) · 2.33 KB
/
jsfile.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <stdio.h>
namespace jsfile { // low-level internal use functions
void deleteFile(char *fileName) {
FILE *f;
f = fopen(fileName, "wb");
fclose(f);
}
bool existsFile(char *fileName) {
FILE *f = fopen(fileName, "r+b");
bool b = f != NULL;
if (b) fclose(f);
return b;
}
void appendFile(char *fileName, void *data, int size) {
FILE *f;
if (existsFile(fileName)) {
f = fopen(fileName, "r+b");
}
else {
f = fopen(fileName, "wb");
}
fseek(f, 0, SEEK_END);
fwrite(data, 1, size, f);
fclose(f);
}
int fileSize(char *n) {
FILE *f;
f = fopen(n, "rb");
if (f) {
fseek(f, 0, 2);
int t;
t = ftell(f);
fseek(f, 0, 0);
fclose(f);
return t;
}
else return -1;
}
char* load(char *fileName, int *filesize=0) { // you must 'delete' returned pointer
//TODO: rewrite to use size and set into var immediately
FILE *f = fopen(fileName, "r");
if (f >= 0) {
int size = fileSize(fileName);
if (filesize) *filesize = size;
if (size < 0) {
return 0;
}
char *s = new char[size];
int l = fread(s, 1, size, f);
fclose(f);
return s;
}
else return 0;
}
}
var readFile(var fileName, var encoding = "utf8") {
var t = fileName;
char *fn = t.getStringAllocUtf();
int size;
char *c = jsfile::load(fn, &size);
if (c == 0) return undefined;
var R;
if (encoding == "binary")
R.setAscii(c);
else if (encoding == "utf16")
R.set_jschar((jschar*)c, size/2);
else R = c;
delete[] fn;
delete[] c;
return R;
}
var writeFile(var fileName, var data, var encoding = "utf8") {
using namespace jsfile;
int dataSize;
char *fn, *d;
fn = fileName.getStringAllocUtf();
if (encoding == "utf8") {
d = data.getStringAllocUtf(&dataSize);
}
else {
d = data.getStringAllocAscii(&dataSize);
}
if (existsFile(fn)) {
deleteFile(fn);
}
appendFile(fn, d, dataSize);
delete[] fn;
delete[] d;
return undefined;
}
var appendFile(var fileName, var data, var encoding = "utf8") {
using namespace jsfile;
int dataSize;
char *fn, *d;
fn = fileName.getStringAllocUtf();
if (encoding == "utf8") {
d = data.getStringAllocUtf(&dataSize);
}
else {
d = data.getStringAllocAscii(&dataSize);
}
appendFile(fn, d, dataSize);
delete[] fn;
delete[] d;
return undefined;
}
var fileExists(var fileName) {
using namespace jsfile;
char *fn, *d;
fn = fileName.getStringAllocUtf();
bool result = existsFile(fn);
delete[] fn;
return result;
}