-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReader.h
91 lines (88 loc) · 1.87 KB
/
Reader.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
#include "uselib.h"
class Reader
{
private:
bool is_eof;
int current_index;
int current_line;
std::string file_content;
public:
Reader(std::string filename) { this->loadFile(filename); };
Reader();
~Reader(){};
void loadFile(std::string filename);
bool eof() { return this->is_eof; };
char peek();
void back();
char getChar();
std::string getLine();
int currLine() { return this->current_line; };
int currIndex() { return this->current_index; };
};
Reader::Reader()
{
this->is_eof = true;
this->file_content.clear();
}
void Reader::loadFile(std::string filename)
{
std::ifstream in(filename);
std::stringstream ss;
if (in.fail())
{
std::cout << "load file fail\n";
exit(1);
}
else
{
ss << in.rdbuf();
this->file_content = ss.str();
this->current_index = 0;
this->current_line = 1;
this->is_eof = false;
}
in.close();
}
char Reader::peek()
{
if (this->is_eof)
return EOF;
if (this->file_content[this->current_index] == '\0')
return '$';
return this->file_content[this->current_index];
}
void Reader::back()
{
if (this->file_content[--this->current_index] == '\n')
this->current_line--;
}
char Reader::getChar()
{
if (!this->is_eof)
{
char c = this->file_content[this->current_index++];
if (c == '\n')
this->current_line++;
if (c == '\0' || (c == '$'))
{
this->is_eof = true;
return '$';
}
return c;
}
return '$';
}
std::string Reader::getLine()
{
std::string str;
while (!this->is_eof)
{
if ((this->peek() == '\n') || (this->peek() == '$') || (this->peek() == '\r'))
{
this->getChar();
break;
}
str += this->getChar();
}
return str;
}