a8/a8/csvreader.cc
2018-08-26 20:34:01 +08:00

90 lines
2.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <a8/a8.h>
#include <a8/stringlist.h>
#include <a8/csvreader.h>
namespace a8
{
CsvReader::CsvReader()
{
}
bool CsvReader::Load(const std::string& filename)
{
columns_.clear();
values_.clear();
currline_ = 0;
bool ret = stringlist_.LoadFromFile(filename.c_str());
if(ret){
if(NextLine()){
for(unsigned int i = 0;i < values_.size(); i++){
columns_.insert(std::pair<std::string, int>(values_[i], i));
}
}
}
return ret;
}
bool CsvReader::NextLine()
{
if(currline_ >= stringlist_.Count()){
return false;
}
values_.clear();
const char *p = stringlist_.String(currline_).c_str();
const char *pv = p;
// printf("%s\n", p);
while(*p && p){
if(*p == ','){
if(p > pv){
values_.push_back(std::string(pv, p - pv));
// printf("%s\n", std::string(pv, p - pv).c_str());
}else{
values_.push_back("");
}
pv = p + 1;
}
p++;
}
if(p && *p == ','){
values_.push_back("");
}else if(p > pv){
values_.push_back(std::string(pv, p - pv));
}
if(columns_.size() - values_.size() == 1){
values_.push_back("");
}
if(columns_.size() > 0){
assert(values_.size() >= columns_.size());
}
currline_++;
return true;
}
a8::XValue CsvReader::GetValue(const char* name)
{
std::map<std::string, int>::iterator itr = columns_.find(name);
if(itr != columns_.end()){
std::string decoestring = values_[itr->second];
a8::ReplaceString(decoestring, "\\n", "\n");
a8::ReplaceString(decoestring, "", ",");
return a8::XValue(decoestring);
}else{
assert(false);
return a8::XValue("");
}
}
a8::XValue CsvReader::GetValue(const std::string& name)
{
return GetValue(name.c_str());
}
bool CsvReader::KeyExists(const std::string& name)
{
auto itr = columns_.find(name);
return itr != columns_.end();
}
}