读取配置文件csv的接口封装类。
csv配置文件既可以在excel中方便编辑,又体积较小,分析速度较快,所以是作为游戏等软件配置文件的较好的选择。
由于csv配置文件没有较好的c++库的支持(目前没见到),可以根据自己的需求编写读取接口库。
使用规则是第一行是各个字段的字段标注,后面的各行是具体的数值。
由于csv比较方便是在windows的excel下编辑,一般是gbk编码的。而服务器程序一般是utf8编码的。根据需求,可以对中文字符串类型的变量进行转码。
代码如下:
#ifndef _CSVFILE_H_
#define _CSVFILE_H_
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <stdlib.h>
#include <iostream>
#include <assert.h>
#include <algorithm>
#include "CodeConvert.h"
#include "assert/mAssert.h"
//该类为读取csv文件接口
//根据字段名称来找到所对应的值
class CSVFile
{
public:
CSVFile()
{
m_pContext = NULL;//文件内容指针
m_pFile = NULL;//文件指针
m_pLinePtr = NULL;//行头指针
}
~CSVFile()
{
if (NULL != m_pContext)
{
delete []m_pContext;
m_pContext = NULL;
}
m_pLinePtr = NULL;
m_pFile = NULL;
}
<span style="white-space:pre"> </span>//读取文件内容到缓存
inline bool Open(bool bIsRead, const char* strPath, const char* strFilename)
{
m_nFileState = FILE_STATE_NULL;
m_sFullFileName = strPath;
m_sFullFileName += strFilename;
m_pFile = fopen(m_sFullFileName.c_str(), "rb");
if(!m_pFile)
{
return false;
}
fseek(m_pFile, 0, SEEK_END);
long size = ftell(m_pFile);
fseek(m_pFile, 0, SEEK_SET);
char *buffer = new char[size + 1];
size_t nRead = fread(buffer, 1, size, m_pFile);
fclose(m_pFile);
if((long)nRead != size)
return false;
buffer[nRead] = 0;
<span style="white-space:pre"> </span>//如果程序编码是 utf8且 cvs配置文件编码是gbk则需要转码为utf8
#if (UTF8 == PROGRAM_CODE) && (GBK == CSV_CODE)
m_pContext = new char[size*2 + 1];
int nConvertedSize = gbk2utf8(m_pContext,size*2,buffer);
m_pContext[nConvertedSize] = '\0';
delete []buffer;
#else
m_pContext = buffer;
#endif
m_pLinePtr = m_pContext;
ReadCSVHead();//读取csv配置文件的第一行(也是配置的各个字段名称)
if (bIsRead)
{
m_nFileState = FILE_STATE_READ;//开始读取文件数据
}
return true;
}
// 读取csv文件中的一行数据
inline bool CSVReadNextRow()
{
if (m_nFileState != FILE_STATE_RE