Easily implement a class for operating the INI file
Author: lixiaosan (9CBS)
Preface:
I believe that many friends need to introduce some data in the program to the program in the program. So this time, a better approach is to write all your data into an INI file, then initialize the line in the program to read the data in the INI file.
Introduction to one .ini
So what is the INI file? The INI file is an abbreviation of Initialization File, which is an intention to initialize the file. (You can see it from the name). Not only your own procedure can use the INI file, in fact, the Windows operating system also has its own INI file - Win.ini, saved in the% windir% / system32 directory. Windows configures the current operating system through this file.
Access to the data in the INI file is to take a pre-approximately dealive "item-value" storage structure, and various data is stored in a stored storage. The following is some of the contents of the Win.ini file.
[Mail] MAPI = 1cmc = 1cmcdllname = Mapi.dllcmcdllname32 = Mapi32.dllmapix = 1Mapixver = 1.0.0.1OLEMESSAGING = 1
Table 1
Through the above, we can see that the INI file divides various data into a number of "[]", and in each "section" contains a lot of "items", "item" is followed by one The equal number, the equal number is the value of this item. In this example [Mail] is a "section", MAPI is an item, 1 is the value of MAPI. Therefore, it's general form we can sum up:
[Section]
Key = KeyValue
two. API operating in INI file
Windows SDK provides two sets of APIs to read and write the INI file.
Read GetPrivateProfileStringGetPrivateProfileIntWritePrivateProfileStringGetPrivateProfileSectionWritePrivateProfileSectionGetPrivateProfileSectionNames GetPrivateProfileStructWritePrivateProfileStruct
Table 2
Read and write getProfileStringgetProfileintWriteProfileStringgetProfileeSECTIONWRITEPRIVATEPROFILESECTION
table 3
For the user's profile, usually we use the function in Table 2, which can see "private" from the function, it is a function of the private configuration file (it is nonsense!). The function in Table 3 is a function provided to the system profile, that is, Win.ini operations. Only the functions in Table 2 are prepared, which is also the highest use rate, the function operation in Table 3 and the function operation class in Table 2, and is omitted. Now let's take a look at the functions of these functions:
DWORD getPrivateProfileString
LPCTSTR LPAPPNAME, / / section name, ie section
LPCTSTR LPKEYNAME, // item name, KEY
LPCTSTR LPDEFAULT, / / The default returns string. Such as LPKEYNAME is not found, copy lpdefault to lpreturnedstring
LPTSTR LPRETURNEDSTRING, / / Return the buffer address of the string
DWord nsize, // buffer size LPCTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTR LPFILENAME // INI File Path
);
Function: Get KeyValue based on the specified section and Key, stored in LPRETURNEDSTRING: Returns the number of characters in the buffer. Does not include end
Uint getprivateprofileint
LPCTSTSTR LPAPPNAME, // section name, ie section lpctstr lpkeyname, // item name, KEY
INT NDEFAULT, / / The default returns an integer value. If lpKeyname is not found, the function returns the value of NDEFAULT
LPCTSTR LPFILENAME // INI file path
);
Function: Get integer keyValue based on the specified section and Key: Return to the integer keyValue
Bool WritePrivateProfileString (LPCTSTSTSTSTSTSTSTSTSTR LPKEYNAME, // item name, ie Key LPCTSTSTSTRING, // To write string LPCTSTR LPFILENAME // INI file path);); Features: To the specified Section and Key write KeyValue. If lpstring is null, delete the current LPKEYNAME if lpkeyname = lpstring = null, remove the current section and all the key below If section or key does not exist, then create; existence override returns: write success.
DWORD getPrivateProfileeSectionNames (LPTSTSTSTSTSTSTSTSTSTSTSZRETURNBuffer, // Store all sections buffer address DWORD nsize, // buffer size LPCTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTR LPFILENAME // INI file path););
Function: Get all Section names in the INI file. Returns: Returns the number of characters copied to the buffer. Does not include the end. Note: Returns all SECTION formats in the buffer are "Section1", 0, "Section2", 0. . . . If you need to get the specific each section, you need to perform a string parsing. An analysis step is seen in the getAllKeysandVALUES function in the later INIFILE class.
Note: Returns all SECTION formats in the buffer are "Section1", 0, "Section2", 0. . . . If you need to get the specific each section, you need to perform a string parsing. An analysis step is seen in the getAllKeysandVALUES function in the later INIFILE class.
DWORD GETPRIVATEPROFILESECTION
LPCTSTR LPAPPNAME, / / section name, ie section
LPTSTR LPRETURNEDSTRING, // Store the buffer address of all Key and KeyValue under section
DWord nsize, // buffer size LPCTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTSTR LPFILENAME // INI File Path
);
Function: Get all KEY and KeyValue under the specified section.
Returns: Returns the number of characters copied to the buffer. Does not include the end.
Note: The return format returned in the buffer is "Key1 = KeyValue1", 0, "Key2 = KeyValue2", 0. . . .
If you need to get specific Key and KeyValue, string parsing is required. The parsing step will be seen in the getAllKeysandVALUES function in the later INIFILE class. GetPrivateProfileStruct and WritePrivateProfileStruct are less, this article has not been introduced, interested friends can look at MSDN themselves, and have a detailed introduction.
And WritePrivateProfileStruct is less, this article has not been introduced, interested friends can look at MSDN themselves, and have a detailed introduction.
DWORD GETPRIVATEPROFILESECTION
LPCTSTR LPAPPNAME, / / section name, ie section
LPTSTR LPRETURNEDSTRING, // Store the buffer address of all Key and KeyValue under section
DWORD nsize, // buffer size
LPCTSTR LPFILENAME // INI file path
);
Function: Get all KEY and KeyValue under the specified section.
Returns: Returns the number of characters copied to the buffer. Does not include the end.
Note: The return format returned in the buffer is "Key1 = KeyValue1", 0, "Key2 = KeyValue2", 0. . . .
If you need to get specific Key and KeyValue, string parsing is required. The parsing step will be seen in the getAllKeysandVALUES function in the later INIFILE class. GetPrivateProfileStruct and WritePrivateProfileStruct are less, this article has not been introduced, interested friends can look at MSDN themselves, and have a detailed introduction.
three. A class of INI
With the above API, we can easily make a simple operation of the INI file.
//
// file: inIfile.h
// Date: October 2004
// Author: lixiaosan
// email: airforcetwo@163.com
// Copyright (c) 2004. All rights reserved.
//
#if! defined (afX_INIFILE_H___B5C0D7F7_8353_4C93_AAA4_38A688CA253C__INCluded_)
#define AFX_INIFILE_H__B5C0D7F7_8353_4C93_AAA4_38A688CA253C__included_
#iF _MSC_VER> 1000
#pragma overce
#ENDIF / / 100 m _ _
Class CiniFile
{
PUBLIC:
CINIFILE ();
Virtual ~ cinifile ();
/ / Set the INI file path // Successfully returns true; otherwise return false
Bool setPath; / / Check if the section exists / / exists back true; otherwise returns false
Bool Sectionexist (CString StRSEC);
/ / Read keyvalue from the specified section and Key Back KeyValue
CString getKeyValue (CString StrSecion,
Cstring strkey);
// Set Section, Key, and KeyValue, create if section or key does not exist
Void setKeyValue (CString StrSection,
CString strkey,
CString strkeyvalue;
/ / Delete a key under the specified section
Void DeleteKey (CString StRSECTION,
Cstring strkey);
/ / Delete the specified section and all of the key
Void deletesection (cstring strsection);
// Get all section // Return to the number of sections
INT Getallsections (CSTRINGARRAY & Strarrse);
/ / Return to KEY and KeyValue // according to the specified section
Int getAllKeysandVALUES (CString StrSection,
CStringArray & Strarrkey,
CStringArray & StrarrkeyValue);
/ / Delete all sections
Void deleteallsections ();
Private:
// INI file path
CString m_strpath;
}
#ENDIF /! Defined (AFX_INIFILE_H__B5C0D7F7_8353_4C93_AAA4_38A688CA253C__INCluded_)
//
// file: inIfile.cpp
// Date: October 2004
// Author: lixiaosan
// email: airforcetwo@163.com
// Copyright (c) 2004. All rights reserved.
//
#include "stdafx.h"
/ / # include "test6.h"
#include "inIfile.h"
#ifdef _Debug
#undef this_file
Static char this_file [] = __ file__;
#define new debug_new
#ENDIF
#define max_section 260 // Section maximum length
#define max_key 260 // KeyVALUES maximum length
#define max_allsections 65535 // All section's maximum length
#define max_allkeys 65535 // All KeyValue's maximum length
//
// construction / destruction
//
CINIFILE :: Cinifile () {
}
CINIFILE :: ~ cinifile ()
{
}
//
// public functions
//
Bool Cinifile :: SetPath (CString Strpath)
{
m_strpath = strpath;
/ / Check if the file exists
DWORD DWFLAG = getFileAttributes ((lpctstr) m_strpath);
// File or path does not exist, return false
IF (0xfffffffff == dwflag)
Return False;
// The path is the directory, return false
IF (file_attribute_directory & dwflag)
Return False;
Return True;
}
BOOL CINIFILE :: SectionExist (CString Strsection)
{
TCHAR ChSECTION [MAX_SECTION];
DWORD DWRETVALUE;
DwretValue = getPrivateProfileString (
(Lpctstr) STRSECTION,
NULL,
_T (""),
ChSECTION,
Sizeof (chsection) / sizeof (tchar),
(Lpctstr) m_strpath);
Return (dwretvalue> 0);
}
CSTRING CINIFILE :: GetKeyValue (cstring strsection,
CString strkey)
{
Tchar chkey [max_key];
DWORD DWRETVALUE;
CSTRING STRKEYVALUE = _t ("");
DwretValue = getPrivateProfileString (
(Lpctstr) STRSECTION,
(LPCTSTR) StrKey,
_T (""),
Chkey,
Sizeof (chkey) / sizeof (tchar),
(Lpctstr) m_strpath);
StrKeyValue = Chkey;
Return strkeyvalue;
}
Void Cinifile :: SetKeyValue (CString StRSECTION,
CString strkey,
CSTRING STRKEYVALUE)
{
WriteprivateProfileString
(Lpctstr) STRSECTION,
(LPCTSTR) StrKey,
(Lpctstr) StrKeyValue,
(Lpctstr) m_strpath);
}
Void Cinifile :: DeleteKey (CString StrKey)
{
WriteprivateProfileString
(Lpctstr) STRSECTION,
(LPCTSTR) StrKey,
NULL, // Write null, remove Key
(Lpctstr) m_strpath);
}
Void Cinifile :: DeleteSection (CString StRSECTION)
{
WriteprivateProfileString
(Lpctstr) STRSECTION,
NULL,
Null, // Write null here, remove the section
(Lpctstr) m_strpath);
}
INT CINIFILE :: GetAllsections (CSTRINGARRAY & StrarRSEC)
{
INT DWRETVALUE, I, J, IPOS = 0;
Tchar Challsections [MAX_ALLSECTIONS];
Tchar chtempsection [max_section];
ZeromeMory (Challsections, Max_Allsections);
ZeromeMory (chTempsection, max_section);
DwretValue = getPrivateProfileeSectionNames
Challsections,
MAX_ALLSES,
m_strpath);
// Because Section is stored in the form of "Section1", 0, "Section2", 0, 0. // So if it is detected two 0, Break
For (i = 0; i { IF (ChallSections [i] == null) { IF (Challsections [i] == ChallSections [i 1]) Break; } } i ; // guarantee data reading strrrsection.removeall (); / / Error array For (j = 0; j
{ ChTempsection [ipos ] = challsections [j]; IF (Challsections "[J] == NULL) { Strarrsection.add (chTempsection); ZeromeMory (chTempsection, max_section); IPOS = 0; } } Return strrSecion.getsize (); } INT CINIFILE :: GetAllKeysandValues (CString StRSECTION, CStringArray & Strarrkey, CStringArray & StrarrkeyValue) { INT DWRETVALUE, I, J, IPOS = 0; Tchar ChallKeysandValues [MAX_ALLKEYS]; Tchar ChTempkeyandValue [max_key]; CString StrtempKey; ZeromeMory (ChallKeysandVALUES, MAX_ALLKEYS); ZeromeMory (ChTempKeyandValue, Max_Key); DwretValue = getPrivateProfileSECTION STRSECTION, ChallKeysandValues, Max_allKeys, m_strpath); / / Because the storage form in the array is "Key1 = KeyValue1", 0, "Key2 = KeyValue2", 0 //, if two consecutive 0 is detected, BREAK For (i = 0; i { IF (ChallKeysandValues [i] == null) { IF (ChallKeysandValues [i] == ChallKeysandVALUES [i 1]) Break; } } i ; strarrkey.removeall (); StrarrKeyValue.RemoveAll (); for (j = 0; j
{ ChTempkeyandValue [ipos ] = challkeysandvalues [j]; IF (ChallKeysandValues [J] == NULL) { Strtempkey = chTEMPKEYANDVALUE; Strarrkey.add (startempkey.find ('=')); StrarrKeyValue.Add (StrtempKey.mid (strTempKey.Find ('=') 1); ZeromeMory (ChTempKeyandValue, Max_Key); IPOS = 0; } } Return strarrkey.getsize (); } Void Cinifile :: deleteallsections () { Int nsecnum; CstringArray strrsection; NSecnum = getAllsections (strrrSection); For (int i = 0; i { WriteprivateProfileString (LPCTSTR) Strarrsection [i], NULL, NULL, (Lpctstr) m_strpath); } } four. example For example, there is a MyFile.ini file, the content is as follows: [student] Number = 40 Male = 25 Female = 15 Average_age = 15 [Computer] CPU = 2.0 Motherboard = asus HardDisk = 120 RAM = 512 Display = Sansung Now add InIfile.h and InIfile.cpp to your project. In use in his class #include "inIfile.h"; CINIFILE FILE; CStringArray Arrsction, Arrkey, ArrkeyValue; File.SetPath ("f: // myfile.ini"); CString str = "" IF (file.sectionexist ("student"))) { // Str = "15" Str = file.getKeyValue ("student", "female"); / / Set Number 50 File.setKeyValue ("Student", "Number", "50"); // Because Computer_Num does not exist in Student, an increase File.setKeyValue ("Student", "Computer_num", "30"); / / Get all sections Int num = file.getallsections (arrsection); Str = ""; For (int i = 0; i { Str = arrsection [i] ""; // str = "student computer"; } / / Get all Key and KeyValue Int num = file.getallkeysandValues ("Computer", Arrkey, ArrkeyValue; Str = "" For (int J = 0; J { // arrkey saves all of the key under Computer // ArrkeyValue saves all KeyValue under Computer Str = arrkey [j]; Str = arrkeyvalue [j]; } / / Delete Computer_num under Student File.deleteKey ("Student", "Computer_Num"); // Delete Student File.DeleteSection ("student"); } Interested friends can expand on this class, add your favorite features. For example, return INT instead of a string. Let's talk about it, welcome everyone to correct. :) Copyright Notice: 9CBS is this BLOG managed service provider. If this paper involves copyright issues, 9CBS does not assume relevant responsibilities, please contact the copyright owner directly with the article Author.