UGDK  0.4.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
reader.h
Go to the documentation of this file.
1 
2 
3 #ifndef UGDK_UTIL_GDD_READER_H_
4 #define UGDK_UTIL_GDD_READER_H_
5 
6 #include <cstdio>
7 #include <string>
8 #include <vector>
9 
11 
12 namespace ugdk {
13 
14 namespace gdd {
15 
16 class Reader {
17 
18  public:
19 
20  Reader(FILE *file) : file_path_("<unknown>"), file_(file), line_(1) {}
21 
22  Reader(const std::string &file_path);
23 
24  ~Reader() {}
25 
26  std::string& file_path() { return file_path_; }
27 
28  size_t line() { return line_; }
29 
30  bool Begin() {
31  file_ = fopen(file_path_.c_str(), "r");
32  return file_ != NULL;
33  }
34 
35  int Next() {
36  int token = fgetc(file_);
37  if (token == '\n')
38  line_++;
39  return token;
40  }
41 
42  void SkipComment() {
43  int token = 0;
44  while ((token = fgetc(file_)) != '\n' && token != EOF);
45  line_++;
46  }
47 
48  void SkipSpace() {
49  int token = 0;
50  while ((token = fgetc(file_)) == ' ' || token == '\t');
51  ungetc(token, file_);
52  }
53 
54  bool IsReserved(int token) {
55  switch (token) {
56  case '#':
57  case '$':
58  case '%':
59  case '@':
60  case '+':
61  case '[':
62  case ']':
63  return true;
64  default:
65  return false;
66  }
67  }
68 
69  bool UntilNextTag() {
70  int token = 0;
71  while ((token = fgetc(file_)) == ' ' || token == '\t');
72  ungetc(token, file_);
73  return !IsReserved(token) && token != '\n' && token != '\r' && token != EOF;
74  }
75 
76  bool Name(std::string &name) {
77  int token = 0;
78  token = fgetc(file_);
80  ERR_BAD_NAME_BEGIN((*this)),
81  false);
82  name.push_back(static_cast<char>(token));
83  for (token = fgetc(file_); VALID_NAME_TOKEN(token); token = fgetc(file_))
84  name.push_back(static_cast<char>(token));
85  ungetc(token, file_);
86  return true;
87  }
88 
89  void Value(std::string &value) {
90  int token = 0;
91  for (token = fgetc(file_); VALID_VALUE_TOKEN(token); token = fgetc(file_))
92  value.push_back(static_cast<char>(token));
93  ungetc(token, file_);
94  }
95 
96  void ValueSequence(std::vector<std::string> &values) {
97  while (UntilNextTag()) {
98  std::string value = "";
99  Value(value);
100  if (value.length() == 0) break;
101  values.push_back(value);
102  }
103  }
104 
105  private:
106 
107  std::string file_path_;
108  FILE *file_;
109  size_t line_;
110 
111 };
112 
113 } /* namespace gdd */
114 
115 } /* namespace ugdk */
116 
117 #endif /* UGDK_UTIL_GDD_READER_H_ */