Easily implement a class for operating the INI file

xiaoxiao2021-03-06  95

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.

I. Incom, 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 = 1

CMC = 1

CMCDLLNAME = Mapi.dll cmcdllname32 = mapi32.dll mappix = 1

Mapixver = 1.0.0.1

OLEMESSAGING = 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. Operation The API Windows SDK of the INI file provides two sets of APIs to read and write the INI file.

Read Write GetPrivateProfileString GetPrivateProfileint WritePrivateProfileString GetPrivateProfileeSection WritePrivateProfilesection GetPrivateProfilesenames

GetPrivateProfileStruct WritePrivateProfileStruct

Table 2

Reading and writing GetProfileString GetProfileSECTION WritePrivateProfileSECTION Table 3 Table 3 For the user's configuration file, usually we use the function in Table 2, which can see "private" from the function. It is a function of private configuration files. (Another 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. DWORD GetPrivateProfileString (LPCTSTR lpAppName, // section name, that Section LPCTSTR lpKeyName, // item name, that Key LPCTSTR lpDefault, // default return the string as lpKeyName not found, copy lpDefault to lpReturnedString LPTSTR lpReturnedString, // return character String buffer address DWORD NSIZE, / / ​​Buffer size LPCTSTSTSTSTSTSTR LPFILENAME // INI file path); Function: Based on the specified section and Key get KeyValue, store it in LPRETURNEDSTRING: Returns the number of characters in the buffer. Does not include the endpper uint getprivateprofileint (LPCTSTSTSTSTSTSTSTSTSTR LPKEYNAME, // Intimin, "KEY INT NDEFAULT, / / ​​default return to the whole value. If lpkeyname is not found, the function returns the value of NDEFAULT LPCTSTR LPFileName // INI file path); Function: Get intellectual keyValue according to the specified section and Key: Return to get the integer KeyValue

Bool WritePrivateProfileString (LPCTSTSTR LPAPPNAME, / / ​​section name, XI) Key writes to KeyValue. If lpString is NULL, delete the current lpKeyName if lpKeyName = lpString = NULL, then delete the current Section and all its Key or Key under Section if does not exist, it is created; there is then covered DWORD GetPrivateProfileSectionNames (LPTSTR lpszReturnBuffer, // store all Section Buffer address DWORD NSIZE, / / ​​Buffer size LPCTSTR LPFILENAME // INI file path); Function: Get all section name 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. DWORD GetPrivateProfileSection (LPCTSTR lpAppName, // section name, i.e. Section LPTSTR lpReturnedString, // DWORD nSize store buffer address and all KeyValue the specified Key Section, // buffer size LPCTSTR lpFileName // ini file path); Function: Specifies give All Key and KeyValue under section 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. After an Ini class has the above API, we can easily make a simple operation INI file class.

//

// 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 (CString StrPath);

/ / Check if the section exists / / exists returns 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 & StrarRSEC);

/ / 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, delete 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 SECTION is in the form of "key1 = keyvalue1", 0, "key2 = keyvalue2", 0 //, if two consecutive 0 is detected, Breakfor (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, add 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 own features. For example, return INT instead of a string. Let's talk about it, welcome everyone to correct. :) Return: Write success.

Now let's take a look at the functions of these functions:

转载请注明原文地址:https://www.9cbs.com/read-97110.html

New Post(0)