00001 /* Copyright (C) 2010 webis.de 00002 * All rights reserved. 00003 */ 00004 #ifndef AITOOLS_INVERTEDINDEX_INVERTED_FILE_WRITER_HPP 00005 #define AITOOLS_INVERTEDINDEX_INVERTED_FILE_WRITER_HPP 00006 00007 #include "Record.hpp" 00008 #include "Exception.hpp" 00009 #include <boost/filesystem/fstream.hpp> 00010 00011 namespace aitools { 00012 namespace invertedindex { 00013 00023 template<typename Value> 00024 class InvertedFileWriter { 00025 00026 public: // class member 00027 00028 static const char delim = '\t'; 00029 00030 public: // c'tor / d'tor 00031 00032 InvertedFileWriter(); 00033 00034 InvertedFileWriter(const bfs::path& path) throw (std::invalid_argument); 00035 00036 ~InvertedFileWriter(); 00037 00038 private: // disallow copying 00039 00040 InvertedFileWriter(const InvertedFileWriter& writer); 00041 00042 InvertedFileWriter& operator=(const InvertedFileWriter& writer); 00043 00044 public: // member 00045 00046 void close(); 00047 00048 bool is_open() const; 00049 00050 const bfs::path& path() const; 00051 00052 void open(const bfs::path& path) throw (std::invalid_argument); 00053 00054 bool write(const Record<Value>& record); 00055 00056 private: // data 00057 00058 bfs::ofstream ofs_; 00059 std::string key_; 00060 bfs::path path_; 00061 00062 }; 00063 00064 // IMPLEMENTATION 00065 00066 template<typename Value> 00067 InvertedFileWriter<Value>::InvertedFileWriter() 00068 {} 00069 00070 template<typename Value> 00071 InvertedFileWriter<Value>::InvertedFileWriter(const bfs::path& path) 00072 throw (std::invalid_argument) 00073 { 00074 open(path); 00075 } 00076 00077 template<typename Value> 00078 InvertedFileWriter<Value>::~InvertedFileWriter() 00079 {} 00080 00081 template<typename Value> 00082 void 00083 InvertedFileWriter<Value>::close() 00084 { 00085 path_ = bfs::path(); 00086 ofs_.close(); 00087 key_.clear(); 00088 } 00089 00090 template<typename Value> 00091 bool 00092 InvertedFileWriter<Value>::is_open() const 00093 { 00094 return ofs_.is_open(); 00095 } 00096 00097 template<typename Value> 00098 const bfs::path& 00099 InvertedFileWriter<Value>::path() const 00100 { 00101 return path_; 00102 } 00103 00104 template<typename Value> 00105 void 00106 InvertedFileWriter<Value>::open(const bfs::path& path) 00107 throw (std::invalid_argument) 00108 { 00109 ofs_.open(path); 00110 if (!ofs_) 00111 { 00112 Exception::throw_invalid_argument("Cannot open", path); 00113 } 00114 path_ = path; 00115 } 00116 00117 template<typename Value> 00118 bool 00119 InvertedFileWriter<Value>::write(const Record<Value>& record) 00120 { 00121 if (key_ != record.key()) 00122 { 00123 if (!key_.empty()) 00124 { 00125 ofs_ << '\n'; 00126 } 00127 ofs_ << record.key(); 00128 key_ = record.key(); 00129 } 00130 ofs_ << '\t' << record.value(); 00131 return ofs_; 00132 } 00133 00134 } // namespace invertedindex 00135 } // namespace aitools 00136 00137 #endif // AITOOLS_INVERTEDINDEX_INVERTED_FILE_WRITER_HPP