C++读取CSV表格 (二)

2014-11-24 03:18:22 · 作者: · 浏览: 1
pEnd = strchr(pBegin, '\n');
}
delete []fileBuffer;
fileBuffer = NULL;
pBegin = NULL;
pEnd = NULL;

map::iterator iter = stringMap.begin();
for (; iter != stringMap.end(); ++iter)
{
vector stringVec;
map stringMapTemp;
assert(GetParamFromString(iter->second, stringVec) > 0);

vector::size_type idx = 0;
for (; idx != stringVec.size(); ++idx)
{
stringMapTemp[idx + 1] = stringVec[idx];
}

m_stringMap[iter->first] = stringMapTemp;
}

fclose(pFile);
m_CSVName = path;
return true;
}
else
{
return false;
}
}

bool CppCSV::SaveCSV(const char *path /* = NULL */)
{
if (path != NULL)
{
m_CSVName = path;
}

FILE *pFile = fopen(m_CSVName.c_str(), "w");
if (pFile)
{
map>::iterator iter = m_stringMap.begin();
for (; iter != m_stringMap.end(); ++iter)
{
map &rStringMap = iter->second;
map::iterator it = rStringMap.begin();
for (; it != rStringMap.end(); ++it)
{
string strTemp = it->second;
strTemp += ',';
fwrite(strTemp.c_str(), 1, 1, pFile);
}

char delim = '\n';
fwrite(&delim, 1, 1, pFile);
}

fclose(pFile);
return true;
}
else
{
return false;
}
}

bool CppCSV::GetIntValue(u32 uiRow, u32 uiCol, int &riValue)
{
string *pStr = GetStringValue(uiRow, uiCol);
if (pStr)
{
riValue = atoi(pStr->c_str());
return true;
}
else
{
return false;
}
}

bool CppCSV::GetFloatValue(u32 uiRow, u32 uiCol, float &rfValue)
{
string *pStr = GetStringValue(uiRow, uiCol);
if (pStr)
{
rfValue = atof(pStr->c_str());
return true;
}
else
{
return false;
}
}

string* CppCSV::GetStringValue(u32 uiRow, u32 uiCol)
{
map>::iterator iter = m_stringMap.find(uiRow);
if (iter != m_stringMap.end())
{
map &rStrMap = iter->second;
map::iterator it = rStrMap.find(uiCol);
if (it != rStrMap.end())
{
return &(it->second);
}
else
{
return NULL;
}
}
else
{
return NULL;
}
}

//用于分割字符串,将CSV表格中的一行按照规则解析成一组字符串,存储在一个vector中
//根据CSV表格中所存储的数据的不同,重载各函数
int CppCSV::GetParamFromString(string str, vector &stringVec, char delim)
{
char *token = strtok(const_cast(str.c_str()), &delim);
while (token)
{
string strTemp = token;
stringVec.push_back(strTemp);
token = strtok(NULL, &delim);
}

return stringVec.size();
}

void CppCSV::GetSkillRecordMapTable(map &sSkillMapTable)
{
map>::iterator iter = m_stringMap.begin();
for (; iter != m_stringMap.end(); ++iter)
{
map strmap = iter->second;
SkillRecord skillTemp;
skillTemp.SetID(atoi(strmap[1].c_str()));
skillTemp.SetPath(strmap[2]);
skillTemp.SetName(strmap[3]);
skillTemp.SetHurt(atoi(strmap[4].c_str()));
skillTemp.SetPlayTime(atoi(strmap