INI File Format and read/write

Source: Internet
Author: User
Tags read ini file

INI file (initialization file), which usually stores the initialization information of a program. An INI file consists of several sections. Each section consists of several keys, and each key can be assigned a corresponding value. Reading and writing an INI file is actually the value of the corresponding key in a section, which can be completed by using several functions.

1. Write information to the win. ini file of the system.

Bool writeprofilestring (name of the lpappname of the lpctstr, // section, is the name of a string that ends with 0, and the name of the // key. It is a string that ends with 0. If it is null, the value of the lpstring // key of the entire section is deleted, which is a string ending with 0. If it is null, the corresponding key is deleted)

2. read information from the win. ini file of the system

DWORD getprofilestring (lptstr lpappname, // node name: lptstr lpkeyname, // key name, read the value of this key: lptstr lpdefault, // if the specified key does not exist, this value is the default value for reading lptstr lpreturnedstring, // a pointer to the buffer, receives the read string DWORD nsize // specify the buffer size pointed by lpreturnedstring)
Uint getprofileint (lpctstr lpappname, // same as the lptstr lpkeyname, // same as the int ndefault // if the specified key name does not exist, this value is used as the default value for reading)

3. write and read your ini

A simple ini example:

[Service]Name=AutoRun  HelperDescription=200ApplicationRootKey64=Software\Wow6432Node\Sepang\AutoRun Modem[Registry]ServiceRootKey=Software\AutoRun Modem ServiceApplicationRootKey=Software\Sepang\AutoRun ModemApplicationRootKey64=Software\Wow6432Node\Sepang\AutoRun Modem

The following example shows how it is generated:

Void XXXXX: onbnclickedwriteinibtn () {// ------------------------------------------ // simulate writing a config. INI // ------------------------------------------ // obtain the EXE execution path. tchar tcexepath [max_path] = {0};: getmodulefilename (null, tcexepath, max_path ); // set the INI path to the same directory of EXE # ifndef config_file # define config_file (text ("config1.ini") # endif // _ tcsrchr () returns the position of the last '\' and returns the pointer tchar * pfind = _ tcsrchr (tcexepath, '\'). If (Pfind = NULL) {return;} * pfind = '\ 0'; cstring szinipath = tcexepath; szinipath + = "\"; szinipath + = config_file; /// vertex // bool writeprivateprofilestring (// lpappname of lpctstr, // The Name Of The node. It is a string ending with 0 // lpkeyname of lpctstr, // The Name Of The Key, is a string ending with 0. If it is null, delete the value of the entire segment // lpctstr lpstring, // key, which is a string ending with 0. If it is null, delete the name of the file to be written by the corresponding key // lpctstr lpfilename. If the INI file is in the same directory as the program, //) You can also use the relative path. Otherwise, you must provide the absolute path. // If ini does not exist, it will automatically create the INI file on szinipath. then write data.: writeprivateprofilestring (text ("service"), text ("name"), text ("autorun helper"), szinipath);: writeprivateprofilestring (text ("service "), text ("Description"), text ("200"), szinipath);: writeprivateprofilestring (text ("Registry"), text ("servicerootkey "), text ("Software \ autorun modem service"), szinipath);: writeprivateprofilestring (text ("Registry"), text (" Pplicationrootkey "), text (" SOFTWARE \ Sepang \ autorun modem "), szinipath);: writeprivateprofilestring (text (" Registry "), text (" applicationrootkey64 "), text ("Software \ wow6432node \ Sepang \ autorun modem"), szinipath); // This indicates that different sections can have identical keys.: writeprivateprofilestring (text ("service"), text ("applicationrootkey64"), text ("Software \ wow6432node \ Sepang \ autorun modem"), szinipath ); // execute the following command to read ------------ ---------------------- If (!: Pathfileexists (szinipath) {return;} tchar szkeyvalue [max_path] = {0}; int nvalue = 0; // returns // DWORD getprivateprofilestring (// lpctstr lpappname, // node name // maid, // key name, read the value of the key // maid, // if the specified key does not exist, this value is the default read value // lptstr lpreturnedstring, // a pointer to the buffer, receives the read string // DWORD nsize, // specify the size of the buffer to which the lpreturnedstring points. // lpfilename // The name of the file that reads the information. If the INI file is in the same directory as the program, // You can also use the relative path. Otherwise, you must provide the absolute path // uint getprivateprofileint (// lpctstr lpappname, // node name // lpctstr lpkeyname, // key name, read the key value // int ndefault, // if the specified key name does not exist, this value is used as the default value for reading // lpctstr lpfilename // same as above // usage: getprivateprofilestring (text ("service"), text ("name"), null, szkeyvalue, max_path, szinipath); nvalue =: getprivateprofileint (text ("service"), text ("Description"), 0, szinipath );}

4.

4. How to determine the number of segments in an INI File

To determine the number of segments in an INI file, the simplest way is to find out all the segments and then count the number of segments. To find out all the node names, use the getprivateprofilesectionnames function. Its prototype is as follows:

Dwordgetprivateprofilesectionnames (

Lptstr lpszreturnbuffer, // point to a buffer to save all the returned node names.

DWORD nsize, // the size of the lpszreturnbuffer parameter.

Lptstr lpfilename // file name. If the INI file is in the same directory as the program,

// You can also use relative paths. Otherwise, you must provide absolute paths.

)

The following is a function used to count the total number of sections in an INI file. Of course, if you need to find the keys and their values in each section at the same time, you can easily find the section name.

/* Count the total number of sections

Separation of node names: if the first character of the chsectionnames array is '\ 0', it indicates there are 0 sections.

Otherwise, start from the first character of the chsectionnames array and look back until a '\ 0' character is found,

If the successor character of this character is not '\ 0', it indicates that the previous character constitutes a node name.

If two '\ 0' characters are found consecutively, the statistics ends. */

Tchar chsectionnames [2048] = {0}; tchar * psectionname; // Save the first address of a node name string found. Int J = 0; // J is used to save the offset of the first address of the next node name string relative to the current I. Int COUNT = 0; // count the number of nodes. : Getprivateprofilesectionnames (chsectionnames, 2048, szinipath); for (I = 0; I <2048; I ++, J ++) {If (chsectionnames [0] = '\ 0') {break; // if the first character is 0, it indicates that there is no section in ini .} If (chsectionnames [I] = '\ 0') {// find a' \ 0', it indicates that J offsets are removed from the forward of this character, is the first address of a node name. Psectionname = & chsectionnames [I-j]; // after a node name is found, the value of J is restored to count the offset of the next node name address. //-1 is assigned because the last character '\ 0' of the node name string is the Terminator and cannot be part of the node name. J =-1; // you can obtain the value of the key in this section when obtaining the node name, provided that we know which keys are in this section. Afxmessagebox (ctionctionname); // display the found information. If (chsectionnames [I + 1] = 0) // is 0 or '\ 0 '? {Break; // when both adjacent characters are 0, all the node names are found and the cycle ends .}}}

 

In the VC program, use the getprivateprofilestring and writeprivateprofilestring functions provided by the system to directly read and write the System Configuration INI file (the INI file in the specified directory ).

Assume that there is a file named TETS. ini in the current directory to save the user name and password. The file format is as follows:

[Section1]

Item1 = huzhifeng

Item2 = 1234565

① Write an INI File

Voidcini_file_testdlg: onbuttonwrite ()

{

// Todo: add your control notification handler code here

Cstringstrsection = "Section1 ";

Cstringstrsectionkey = "Item1 ";

Charstrbuff [256];

Cstringstrvalue = _ T ("");

Cstringstrfilepath;

Strfilepath = getcurrentdirectory (256, strbuff); // obtain the current path.

Strfilepath. Format ("% s \ test. ini", strbuff );

Getdlgitemtext (idc_edit_name, strvalue); // obtain the text box content, that is, name.

// Write fields to the INI file.

Writeprivateprofilestring (strsection, strsectionkey, strvalue, strfilepath );

Strsectionkey = "item2 ";

Getdlgitemtext (idc_edit_password, strvalue); // obtain the text box content, that is, the password.

Writeprivateprofilestring (strsection, strsectionkey, strvalue, strfilepath );

}

② Read INI File Content

Void cini_file_testdlg: onbuttonread ()

{

// Todo: add your control notification handler code here

Cstring strsection = "Section1 ";

Cstring strsectionkey = "Item1 ";

Char strbuff [256];

Cstring strvalue = _ T ("");

Cstring strfilepath;

Strfilepath = getcurrentdirectory (256, strbuff); // obtain the current path

Strfilepath. Format ("% s \ test. ini", strbuff );

// Read the content of the corresponding field in the INI File

Getprivateprofilestring (strsection, strsectionkey,

Null, strbuff,

80, strfilepath );

Strvalue = strbuff;

Setdlgitemtext (idc_edit_name, strvalue );

Strsectionkey = "item2 ";

Getprivateprofilestring (strsection, strsectionkey,

Null, strbuff,

80, strfilepath );

Strvalue = strbuff;

Setdlgitemtext (idc_edit_password, strvalue );

Updatedata (false );

}

 

Source of the original article: (half yunyun) Zeng document teacher

Http://hi.baidu.com/__%B6%C0%B9%C2%B2%D0%D4%C6__/blog/item/79957c127edbd9c9c3fd78d0.html

Boolisfileexist (const char * szfilename) // checks whether the object exists

{

Cfilestatus Stat;

If (cfile: getstatus (szfilename, STAT ))

Return true;

Else

Return false;

}

 

// Read the string

Intreadinistring (cstring inifilename, cstring inisection, cstring key, cstring & Value ){

If (inifilename = "" | inisection = "" | key = "") // The parameter is incorrect.

{

Value. Format ("% s", _ T (""));

Return-1;

}

If (! Isfileexist (lptstr) (lpctstr) inifilename) // The INI file does not exist.

{

Value. Format ("% s", _ T (""));

Return-2;

}

: Getprivateprofilestring (inisection, key, "", value. getbuffer (max_path ),

Max_path, inifilename );

Return 0;

}

 

// Read the integer variable

Intreadiniuint (cstring inifilename, cstring inisection, cstring key, uint & value)

{

If (inifilename = "" | inisection = "" | key = "") // The parameter is incorrect.

{

Value = 0;

Return-1;

}

If (! Isfileexist (lptstr) (lpctstr) inifilename) // The INI file does not exist.

{

Value = 0;

Return-2;

}

Value =: getprivateprofileint (inisection, key, 0, inifilename );

Return 0;

}

 

// Obtain the path of the application

Intgetapppath (cstring & apppath)

{

Try

{

Cstring moudlefile;

// Obtain the absolute file path

Getmodulefilename (null, moudlefile. getbuffersetlength (max_path + 1), max_path );

Int Pos = moudlefile. reversefind (_ T ('\\'));

Apppath = moudlefile. Left (Pos + 1 );

} Catch (...){

Return-1;

}

Return 0;

}

 

// Call related functions for button events

Voidcreadwriteinifiedlg: onbutton1 ()

{

// Todo: add your control notification handler code here

Cstring filepath;

// Cstring strservertoieclientport;

Uint iservertoieclientport;

Getapppath (filepath );

M_inifilename.format ("% SCC. ini", filepath );

// Readinistring (m_inifilename, "serverhost", "Port", strservertoieclientport );

Readiniuint (m_inifilename, "serverhost", "Port", iservertoieclientport );

Readinistring (m_inifilename, "serverhost", "datafilename", strservertoieclientport );

}

 

// Determine whether a file exists

Boolisfileexist (const char * szfilename)

{

Cfilestatus Stat;

If (cfile: getstatus (szfilename, STAT ))

Return true;

Else

Return false;

}

 

Intcsetdbdata: getinidata (cstring inifilename, cstring inisection,

Cstring key, cstring & value)

{

If (inifilename = "" | inisection = "" | key = "") // The parameter is incorrect.

{

Value. Format ("% s", _ T (""));

Return-1;

}

If (! Isfileexist (lptstr) (lpctstr) inifilename) // The INI file does not exist.

{

Value. Format ("% s", _ T (""));

Return-2;

}

: Getprivateprofilestring (inisection, key ,"",

Value. getbuffer (max_path), max_path, inifilename );

Return 0;

}

 

Intcsetdbdata: setinidata (cstring inifilename, cstring inisection,

Cstring key, cstring value)

{

If (inifilename = "" | inisection = "" | key = "") // The parameter is incorrect.

{

Value. Format ("% s", _ T (""));

Return-1;

}

If (! Isfileexist (lptstr) (lpctstr) inifilename) // The INI file does not exist.

{

Value. Format ("% s", _ T (""));

Return-2;

}

: Writeprivateprofilestring (inisection, key, value, inifilename );

Return 0;

}

 

// Delete the key

Intcsetdbdata: delinidata (cstring inifilename, cstring inisection)

{

If (inifilename = "" | inisection = "") // The parameter is incorrect.

{

Return-1;

}

If (! Isfileexist (lptstr) (lpctstr) inifilename) // The INI file does not exist.

{

Return-2;

}

: Writeprivateprofilestring (inisection, null, null, inifilename );

Return 0;

}

 

 

A small instance of reading and writing INI files on the window Platform

Http://hi.baidu.com/zerowwj/blog/item/5b088ea790fc429ad043586f.html

/* Read and write INI files */

# Include <iostream>

# Include <windows. h>

# Include <atlstr. h>

Usingnamespace STD;

Voidmain ()

{

Cstring strname;

Cstring strtemp;

Int Nage;

Strname = "zhangsan ";

Nage = 12;

/*

* This function writes a configuration item record to the stud. ini file:

* The configuration item name is "studentinfo", and the configuration item name is name;

* The value is the content referred to by the strname variable of the cstring type.

*/

: Writeprivateprofilestring ("studentinfo", "name", strname, "d: \ stud. ini ");

/*

* This function writes a configuration item record to the stud. ini file:

* The configuration item name is "studentinfo", and the configuration item name is age;

* The value is the content specified by the int type variable Nage, but must be converted to the cstring type before

* Specify the path and name of the file to be written.

*/

Strtemp. Format ("% d", Nage );

: Writeprivateprofilestring ("studentinfo", "Age", strtemp, "d: \ stud. ini ");

/*

* The following is the reading method. The reading method of the cstring type is different from that of the int type. For specific functions of the function, see msdn

*/

Cstring strstudname;

Int nstuage;

: Getprivateprofilestring ("studentinfo", "name", "defualt ",

Strstudname. getbuffer (max_path ),

Max_path, "d :\\ stud. ini ");

Nstuage =: getprivateprofileint ("studentinfo", "Age", 10, "d: \ stud. ini ");

Cout <"strstudname =" <strstudname <Endl;

Cout <"nstuage =" <nstuage <Endl;

}

 

 

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.