Go to the documentation of this file.00001 #ifndef BWI_TOOLS_RECORD_WRITER_H
00002 #define BWI_TOOLS_RECORD_WRITER_H
00003
00004 #include <fstream>
00005 #include <map>
00006 #include <string>
00007 #include <vector>
00008
00009 #include <boost/algorithm/string/join.hpp>
00010 #include <boost/foreach.hpp>
00011 #include <boost/range/adaptor/map.hpp>
00012 #include <boost/range/algorithm/copy.hpp>
00013
00014 namespace bwi_tools {
00015
00016 inline bool writeRecordsAsCSV(const std::string &filename,
00017 const std::vector<std::map<std::string, std::string> > &records) {
00018
00019
00020 std::set<std::string> all_keys;
00021 typedef std::map<std::string, std::string> StringMap;
00022 BOOST_FOREACH(const StringMap& record, records) {
00023
00024 boost::copy(record | boost::adaptors::map_keys, std::inserter(all_keys, all_keys.begin()));
00025 }
00026
00027
00028 std::ofstream ofs(filename.c_str());
00029 if (!ofs.is_open()) {
00030 return false;
00031 }
00032 ofs << boost::algorithm::join(all_keys, ",") << std::endl;
00033
00034
00035 BOOST_FOREACH(const StringMap& record, records) {
00036 std::vector<std::string> vals;
00037 BOOST_FOREACH(const std::string& key, all_keys) {
00038 StringMap::const_iterator value_iter = record.find(key);
00039 if (value_iter == record.end()) {
00040 vals.push_back("0");
00041 } else {
00042 vals.push_back(value_iter->second);
00043 }
00044 }
00045 ofs << boost::algorithm::join(vals, ",") << std::endl;
00046 }
00047
00048 ofs.close();
00049 }
00050
00051 }
00052
00053 #endif