00001 /* Copyright (C) 2010 webis.de 00002 * All rights reserved. 00003 */ 00004 #ifndef AITOOLS_INVERTEDINDEX_INVERTED_FILE_READER_HPP 00005 #define AITOOLS_INVERTEDINDEX_INVERTED_FILE_READER_HPP 00006 00007 #include "RecordReader.hpp" 00008 #include <boost/filesystem/fstream.hpp> 00009 00010 namespace bfs = boost::filesystem; 00011 00012 namespace aitools { 00013 namespace invertedindex { 00014 00048 template<typename Value> 00049 class InvertedFileReader : public RecordReader<Value> { 00050 00051 public: // c'tor / d'tor 00052 00053 InvertedFileReader(); 00054 00055 InvertedFileReader(const bfs::path& path) throw (std::invalid_argument); 00056 00057 ~InvertedFileReader(); 00058 00059 public: // methods 00060 00061 void close(); 00062 00063 bool is_open() const; 00064 00065 const bfs::path& path() const; 00066 00067 bool next(Record<Value>& record); 00068 00069 void open(const bfs::path& path) throw (std::invalid_argument); 00070 00071 private: // data 00072 00073 bfs::ifstream ifs_; 00074 std::string key_; 00075 bfs::path path_; 00076 00077 }; 00078 00079 // IMPLEMENTATION 00080 00081 template<typename Value> 00082 InvertedFileReader<Value>::InvertedFileReader() 00083 {} 00084 00085 template<typename Value> 00086 InvertedFileReader<Value>::InvertedFileReader(const bfs::path& path) 00087 throw (std::invalid_argument) 00088 { 00089 open(path); 00090 } 00091 00092 template<typename Value> 00093 InvertedFileReader<Value>::~InvertedFileReader() 00094 {} 00095 00096 template<typename Value> 00097 void 00098 InvertedFileReader<Value>::close() 00099 { 00100 ifs_.close(); 00101 key_.clear(); 00102 path_ = bfs::path(); 00103 } 00104 00105 template<typename Value> 00106 bool 00107 InvertedFileReader<Value>::is_open() const 00108 { 00109 return ifs_.is_open(); 00110 } 00111 00112 template<typename Value> 00113 const bfs::path& 00114 InvertedFileReader<Value>::path() const 00115 { 00116 return path_; 00117 } 00118 00119 template<typename Value> 00120 bool 00121 InvertedFileReader<Value>::next(Record<Value>& record) 00122 { 00123 while (ifs_.good()) 00124 { 00125 switch (ifs_.peek()) 00126 { 00127 case ' ': 00128 case '\t': 00129 ifs_.get(); 00130 break; 00131 case '\r': 00132 case '\n': 00133 ifs_ >> key_; 00134 break; 00135 default: 00136 record.key().assign(key_); 00137 ifs_ >> record.value(); 00138 return true; 00139 } 00140 } 00141 return false; 00142 } 00143 00144 template<typename Value> 00145 void 00146 InvertedFileReader<Value>::open(const bfs::path& path) 00147 throw (std::invalid_argument) 00148 { 00149 ifs_.open(path); 00150 if (!ifs_) 00151 { 00152 Exception::throw_invalid_argument("Cannot open", path); 00153 } 00154 ifs_ >> key_; // Read first key 00155 } 00156 00157 } // namespace invertedindex 00158 } // namespace aitools 00159 00160 #endif // AITOOLS_INVERTEDINDEX_INVERTED_FILE_READER_HPP