#include <iostream>#include <stdio.h>#include <fstream>#include <tchar.h>#include <conio.h>#include <io.h>#include <Windows.h>#include <string.h>using namespace std;#define NOPRO 0#define INSECTION 1#define INKEY 2#define INVAL 3struct KEY{ string name; string val; KEY* next;};struct SECTION{ string name; KEY *Key; SECTION *next;};class INIReader{private: int state; SECTION *SECTION_head; int CreateSection(SECTION *nowpos); int CreateKey(KEY *nowpos); int ReadINI(FILE *File_In);public: INIReader() { state=NOPRO; SECTION_head=new SECTION; } int LoadFile(char* FilePath,char* ReadMode); int PrintFile();};int INIReader::LoadFile(char *FilePath,char *ReadMode){ FILE *File_In=NULL; File_In=fopen(FilePath,ReadMode); if (File_In) { ReadINI(File_In); } else { return 0; } fclose(File_In); return 1;}int INIReader::CreateKey(KEY *nowpos){ KEY *tmp=new KEY; tmp->next=NULL; nowpos->next=tmp; return 1;}int INIReader::CreateSection(SECTION *nowpos){ SECTION *tmp=new SECTION; tmp->Key=NULL; tmp->next=NULL; nowpos->next=tmp; return 1;}int INIReader::ReadINI(FILE *File_In){ SECTION *nowsec=SECTION_head; KEY *nowkeyhead=NULL; KEY *nowkey=NULL,*prekey=NULL; string data=""; char ch=fgetc(File_In); while (ch!=EOF) { if (ch=='[') {// 删除上一字段产生的多余的Key if (prekey) { delete prekey->next; prekey->next=NULL; } state=INSECTION; CreateSection(nowsec); nowsec=nowsec->next; ch=fgetc(File_In); continue; } if (ch==']') { state=INKEY; nowsec->name=data; data.clear(); nowkey=new KEY; nowsec->Key=nowkey; ch=fgetc(File_In); continue; } if (ch=='='&&state==INKEY) { state=INVAL; nowkey->name=data; data.clear(); ch=fgetc(File_In); continue; } if (state==INVAL&&ch=='\n') { state=INKEY; nowkey->val=data; CreateKey(nowkey); prekey=nowkey; nowkey=nowkey->next; data.clear(); ch=fgetc(File_In); continue; } data+=ch; ch=fgetc(File_In); }/// 删除程序产生的多余Key if(nowkey) { delete nowkey; prekey->next=NULL; } return 1;}int INIReader::PrintFile(){ SECTION *tmpsec=SECTION_head; while(tmpsec->next!=NULL) { tmpsec=tmpsec->next; cout<<tmpsec->name.data()<<endl; KEY *tmpkey=tmpsec->Key; while(tmpkey->next!=NULL) { tmpkey=tmpkey->next; cout<<tmpkey->name.data()<<"="<<tmpkey->val.data()<<endl; } } return 1;}

评论