Interface wrapper class for reading configuration file csv

Source: Internet
Author: User

Read the interface wrapper class for the configuration file CSV.

CSV profiles are easy to edit in Excel, smaller in size and faster to analyze, so they are a good choice for software profiles such as games.

Since the CSV configuration file does not have a good C + + library support (not currently seen), you can write the Read interface library according to your own requirements.

The use rule is that the first row is the field label for each field, and the subsequent lines are the specific values.

Since CSV is easier to edit under Windows Excel, it is generally GBK encoded. The server program is generally UTF8 encoded. Depending on your needs, you can transcode variables of the Chinese string type.

The code is as follows:

#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"//the class to read the CSV file interface//According to the field name to find the corresponding value class CSVFile { Public:csvfile () {m_pcontext = null;//file content pointer m_pfile = null;//file pointer m_plineptr = null;//costume Pointer}~csvfile () {if (NULL! = M_pcont EXT) {Delete []m_pcontext;m_pcontext = NULL;} M_plineptr = Null;m_pfile = NULL;} <span style= "White-space:pre" ></span>//read file contents to cache 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 >//If the program code is UTF8 and the CVS profile encoding is GBK, you need to transcode to utf8#if (UTF8 = Program_code) && (GBK = csv_code) M_pcontext = new Char[s Ize*2 + 1];int nconvertedsize = Gbk2utf8 (M_pcontext,size*2,buffer); m_pcontext[nconvertedsize] = ' ';d elete []buffer;# Elsem_pcontext = buffer; #endifm_pLinePtr = M_pcontext; Readcsvhead ();//Read the first line of the CSV configuration file (also the individual field name of the configuration) if (bisread) {m_nfilestate = file_state_read;//start reading the file data}return true;} Reads a row of data from a CSV file inline bool Csvreadnextrow () {if (m_nfilestate! = file_state_read) return false;const char* sline = m_pline ptr;//Costume const char* slineend = STRCHR (sline, ' \ n ');//Line End if (!slineend) {return false;} M_plineptr = Slineend + 1;if (slineend[-1] = = ' \ r ')//Remove the line break of the Windows file ' \ R ' slineend--;//a line of content empty if (0 = = (slineend-sline)) ret Urn false; Rowparse (sline, int (slineend-sline), m_csvcurrow);//Read the row data return true;} Template<class t>bool csvread (const char* strfieldname, t& TArget)//Based on the field name, read the corresponding value of the row {std::string data;if (m_nfilestate! = File_state_read) {return false;} int n = FindField (strfieldname);//Gets the field name in the number of columns if (n = =-1 | | n >= (int) m_csvcurrow.size ()) {return false;}  data = m_csvcurrow[n];//The value of CONVERT (Target,data), based on the number of columns in the field name, return true; } inline bool Csvread (const char* strfieldname, char* target,size_t len)//According to the field name, read the corresponding value in the row {std::string data;if (m_nfil EState! = File_state_read) {return false;} int n = FindField (strfieldname);//Gets the field name in the number of columns if (n = =-1 | | n >= (int) m_csvcurrow.size ()) {return false;} data = m_csvcurrow[n];//The value, based on the number of columns in the field name, convert (target,len,data); return true;} Template<class t>bool csvwrite (const char* strfieldname, T data)//write interface, currently not using {if (m_nfilestate! = File_state_write ) {return false;} int n = FindField (strfieldname);//Find the number of columns where the field name is located if (n = =-1) {return false;} Std::stringstream ss;ss << Data;m_csvcurrow[n] = Ss.str (); return true;} Get Total row number inline size_t Gettotalrow () {const char* sline = m_pcontext;const char* slineend = StRCHR (sline, ' \ n '); size_t ncount = 0;while (slineend) {slineend = STRCHR (slineend, ' \ n '); if (slineend) {ncount++;slineend+ +;} else break;} return nCount-1;} Data type conversion//conversion to Charinline void convert (char& target,const std::string& str) {if (Str.empty ()) {target = (char) 0;} Else{target = Str.c_str () [0];if (target>= ' 0 ' && target <= ' 9 ') {target = target-' 0 ';}}} Convert to unsigned charinline void convert (unsigned char& target,const std::string& str) {if (Str.empty ()) {target = ( unsigned char) 0;} Else{target = (unsigned char) str.c_str () [0];if (target>= ' 0 ' && target <= ' 9 ') {target = target-' 0 ';}}} Convert to Shortinline void convert (short& target,const std::string& str) {if (Str.empty ()) {target = (short) 0;} Else{target = (short) atoi (Str.c_str ());}} Convert to unsigned shortinline void convert (unsigned short& target,const std::string& str) {if (Str.empty ()) {target = (unsigned short) 0;} Else{target = (unsigned short) atoi (Str.c_str ());}} Convert to Intinline void convert (int&Amp Target,const std::string& str) {if (Str.empty ()) {target = (int) 0;} Else{target = Atoi (Str.c_str ());}} Convert to Intinline void convert (unsigned int& target,const std::string& str) {if (Str.empty ()) {target = (unsigned int ) 0;} Else{target = (unsigned int) atol (STR.C_STR ());}} Convert to long (to 64 bits, it is recommended not to use long and long long,long under 64-bit win is 4 bytes, under 64-bit Linux is 8 bytes) of the inline void convert (long& target,const std::string& str) {if (Str.empty ()) {target = (long) 0;} Else{target = (long) Atol (Str.c_str ());}} Convert to unsigned longinline void convert (unsigned long& target,const std::string& str) {if (Str.empty ()) {target = (u Nsigned long) 0;}                         Else{target = (unsigned long) strtoul (Str.c_str (), null,0); char *endptr = NULL;}} Convert to Long doubleinline void convert (long double& target,const std::string& str) {if (Str.empty ()) {target = (long D ouble) 0;} Else{target = (long double) Atoll (Str.c_str ());}} Convert to Long longinline void convert (long long& target,const std::string& str) {if (Str.empty ()) {target = (long long) 0;} Else{target = (long Long) Atoll (Str.c_str ());}} Convert to Floatinline void convert (float& target,const std::string& str) {if (Str.empty ()) {target = 0;} Else{char *endptr = Null;target = (float) strtod (Str.c_str (), &endptr), if (Endptr && endptr[0]) {target = 0;STD :: cout << "config data error:" <<endptr << Std::endl;}} Convert to Doubleinline void convert (double& target,const std::string& str) {if (Str.empty ()) {target = 0;} Else{char *endptr = Null;target = Strtod (Str.c_str (), &endptr), if (Endptr && endptr[0]) {target = 0;std::cout & lt;< "config data error:" <<endptr << Std::endl;}}        Convert to const char *inline void convert (const char *target,size_t targetlen,const std::string& str) {if (Str.empty ()) { Bzero ((char *) target,targetlen); return;} #if (UTF8 = = Program_code) && (GBK = = Csv_code) Gbk2utf8 (Target,targetlen,str.c_str ()); #elsestrncpy ((char *) Target,str.c_str (), targetlen); #endiFif (Targetlen <= str.length ())//Last Byte place 0* (char *) (target + targetLen-1) = 0;} Convert to char *inline void convert (char *target,size_t targetlen,const std::string& str) {if (Str.empty ()) {bzero (target , Targetlen); return;} #if (UTF8 = = Program_code) && (GBK = = Csv_code) Gbk2utf8 (target, (int) targetlen,str.c_str ());//convert GBK encoding to UTF8 encoding # elsestrncpy (Target,str.c_str (), Targetlen); if (Targetlen <= str.length ()) target[targetlen-1] = 0; #endif}//into std: : stringinline void Convert (std::string& target,const std::string& str) {if (Str.empty ()) {target.clear (); return;} #if (UTF8 = = Program_code) && (GBK = = Csv_code) Gbk2utf8 (Target,str.c_str ()); #elsetarget = str; #endif}//converted to long L Ongvoid convert (Long long& target,const std::string& str) {if (Str.empty ()) {target = 0;} Else{char *endptr = Null;target = (long Long) strtod (Str.c_str (), &endptr), if (Endptr && endptr[0]) {target = 0; Std::cout << "config data error:" <<endptr << Std::endl;}}  PrivateThe container that holds each line of content typedef std::vector<std::string> rowvec;//reads the field noun row and saves it inline void Readcsvhead () {Const char* sline = m_plineptr;//Costume const char* slineend = STRCHR (sline, ' \ n ');//Line tail if (slineend) {m_plineptr = Slineend + 1;if (slineend[-1] = = ' \ R ') slineend--;} Else sline = Slineend = ""; Rowparse (sline, int (slineend-sline), m_csvhead);} Strrow is the starting position of a row in a CSV file//nsize the length of a line//result the string of individual fields of a line inline void Rowparse (const char* strrow, int nSize, Rowvec & result) {result.clear (); std::string strcurword;for (int i = 0; i < nSize; ++i) {char ch = strrow[i];bool Bisadd = t Rue;switch (CH) {case ', ': {//an end result.push_back (strcurword); Strcurword = ""; bisadd = false;} Break;case ' "'://Remove Space case ': case ' \ R '://Remove \rcase ' \ t '://Remove \t{bisadd = false;} Break;default:break;}; if (Bisadd)//Add legal character strcurword + = ch;} Result.push_back (Strcurword);} Remove the ' \ R ' character from the string inline void Delete_r (std::string &str) {while (1) {Std::string::iterator it = Std::find (Str.begin (), Str.end (), ' \ R '); if (it = = Str.end ()) break;str.erASE (it);}}  Strrow is the field in the Program//return field column number inline int FindField (const char* strrow)//Gets the field name corresponding to the number of columns {#if (UTF8 = = Program_code) && (GBK = = Csv_code) std::string Tarstr;gbk2utf8 (Tarstr,strrow); #endifif (m_nfilestate = file_state_null) return-1;for ( Rowvec::iterator it = M_csvhead.begin (); It! = M_csvhead.end (); it++) {#if (UTF8 = = Program_code) && (GBK = = Csv_code) if (*it = = tarstr) {return int (it-m_csvhead.begin ());} #elseif (*it = = Strrow) {return int (it-m_csvhead.begin ());} #endif}printf ("field (%s) not found, config file is (%s) \ n", Strrow,m_sfullfilename.c_str ()), Assert_fail ("profile field not found"); return 0;}  Enum Filestate{file_state_null,//uninitialized File_state_read,//File writable File_state_write,//File readable};  Filestate m_nfilestate;//file state machine//std::fstream m_csvfile;  file* m_pfile;char* m_pcontext;const char* m_plineptr;//row record pointer Rowvec m_csvhead;  Field name Line Rowvec M_csvcurrow;  Current content line std::string m_sfullfilename;//file name full path}; #endif//_csvfile_h_


Interface wrapper class for reading configuration file csv

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.