#include "stdafx.h" #include "TokenlizedFile.h" #include inline std::string& Trim(std::string& str) { const size_t nBeginPos = str.find_first_not_of(" \t\r\n"); if (nBeginPos != std::string::npos) { str.erase(str.begin(), str.begin() + nBeginPos); } const size_t nEndPos = str.find_last_not_of(" \t\r\n"); if (nEndPos != std::string::npos && nEndPos != str.size()) { str.erase(str.begin() + nEndPos + 1, str.end()); } return str; } CTokenlizedFile::ColumnInfo::ColumnInfo(const char* szColumnName) : m_dwHashKey(Math::HashFunc::sdbmHash(reinterpret_cast(szColumnName))), m_szColumnName(szColumnName) { } CTokenlizedFile::ColumnInfo::ColumnInfo(std::string& szColumnName) : m_dwHashKey(Math::HashFunc::sdbmHash(reinterpret_cast(szColumnName.c_str()))), m_szColumnName(szColumnName) { } CTokenlizedFile::CTokenlizedFile(const char* lpszDelimiter) : m_lpFile(NULL), m_nLine(0) { strncpy(m_szDelimiter, lpszDelimiter, MAX_DELIMITER_NUM - 1); m_szDelimiter[MAX_DELIMITER_NUM - 1] = '\0'; m_ColumnInfo.reserve(DEFAULT_COLUMN_NUM); m_ColumnValues.reserve(DEFAULT_COLUMN_NUM); } CTokenlizedFile::~CTokenlizedFile() { } void CTokenlizedFile::Close() { if(NULL != m_lpFile) { fclose(m_lpFile); } m_ColumnInfo.clear(); m_ColumnValues.clear(); } bool CTokenlizedFile::Open(const char* szFilename, const char* szOpenMode) { Close(); m_nLine = 0; m_lpFile = fopen(szFilename, szOpenMode); return (NULL != m_lpFile) ? true : false; } bool CTokenlizedFile::ReadColumn() { char szBuffer[MAX_LINE_BUFFER]; m_ColumnInfo.clear(); if(NULL != fgets(szBuffer, MAX_LINE_BUFFER, m_lpFile)) { char* szToken = strtok(szBuffer, m_szDelimiter); do { m_ColumnInfo.push_back(ColumnInfo(Trim(std::string(szToken)))); } while(NULL != (szToken = strtok(NULL, m_szDelimiter))); ++m_nLine; return true; } return false; } bool CTokenlizedFile::ReadLine() { char szBuffer[MAX_LINE_BUFFER]; m_ColumnValues.clear(); if(NULL != fgets(szBuffer, MAX_LINE_BUFFER, m_lpFile)) { char* szToken = strtok(szBuffer, m_szDelimiter); do { m_ColumnValues.push_back(Trim(std::string(szToken))); } while(NULL != (szToken = strtok(NULL, m_szDelimiter))); ++m_nLine; return true; } return false; } const char* CTokenlizedFile::GetStringValue(const char* szColumnName) { DWORD dwHashkey = Math::HashFunc::sdbmHash(reinterpret_cast(szColumnName)); for(ColumnArray::iterator itr = m_ColumnInfo.begin(); itr != m_ColumnInfo.end(); ++itr) { const ColumnInfo& columnInfo = *itr; if(dwHashkey == columnInfo.m_dwHashKey) { if(0 == strcmp(szColumnName, columnInfo.m_szColumnName.c_str())) { size_t nDistance = itr - m_ColumnInfo.begin(); return GetStringValue(nDistance); } } } return NULL; }