-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmapfile.cpp
82 lines (66 loc) · 1.22 KB
/
mapfile.cpp
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
/*
TODO: use C++ ifstream instead of C fopen
implement better error checks such as if someone tries to write to a read-only file
*/
#include "mapfile.h"
MapFile::MapFile() {
}
MapFile::~MapFile() {
if (fp) {
fclose(fp);
}
}
int MapFile::openRead(const string& filename) {
return open("r", filename);
}
int MapFile::openWrite(const string& filename) {
return open("w", filename);
}
int MapFile::open(const string& fmode, const string& filename) {
fp = fopen(filename.c_str(), fmode.c_str());
if (!fp)
return 1;
fseek(fp, 0, SEEK_SET);
return 0;
}
int MapFile::write(const string& data) {
if (!fp)
return 1;
try {
long current_pos = ftell(fp);
std::fseek(fp, 0, SEEK_END);
string tmp = data + '\n';
fputs(tmp.c_str(), fp);
fseek(fp, current_pos, SEEK_SET);
return 0;
}
catch (int e) {
return 1;
}
}
void MapFile::close() {
if (fp) {
fclose(fp);
fp = NULL;
}
}
string MapFile::read() {
// Read a single line
if (fp) {
string buffer;
/*
char *lineBuffer = (char *)malloc(sizeof(char) * 4096);
if (lineBuffer == NULL)
return "";
*/
char ch = fgetc(fp);
while ((ch != '\n') && (ch != EOF)) {
buffer += ch;
ch = fgetc(fp);
}
return buffer;
}
else {
return "";
}
}