Manipulating the INI file with Visual C + + __c++

Source: Internet
Author: User
Tags delete key function prototype
In our program, there are always some configuration information needs to be saved, in order to complete the function of the program, the easiest way is to write this information in the INI file, the program is initialized to read again. The specific application is as follows:

I. Write information to the. ini file.

1. The WINAPI function prototype used is:

BOOL WritePrivateProfileString (
LPCTSTR Lpappname,
LPCTSTR Lpkeyname,
LPCTSTR lpstring,
LPCTSTR lpFileName
);

The meaning of each of these parameters:

LPCTSTR Lpappname is a field name in the INI file.

LPCTSTR Lpkeyname is a key name under Lpappname, popularly speaking is variable name.

LPCTSTR lpstring is a key value, which is the value of a variable, but must be of type LPCTSTR or CString.

LPCTSTR lpFileName is the full INI file name.

2. Specific use: the establishment of a current student, the need to put his name and age into the C:/stud/student.ini file.

CString strname,strtemp;
int nage;
Strname= "John";
nage=12;
:: WritePrivateProfileString ("Studentinfo", "Name", StrName, "C://stud//student.ini");

The contents of this C:/stud/student.ini file are as follows:

[Studentinfo]
Name= John

3. To save the student's age, simply change the integer value to a character type:

Strtemp.format ("%d", nage);
:: WritePrivateProfileString ("Studentinfo", "Age", strtemp, "C://stud//student.ini");
Two. Read the information from the INI file into the variables in the program.

1. The WINAPI function prototype used is:

DWORD GetPrivateProfileString (
LPCTSTR Lpappname,
LPCTSTR Lpkeyname,
LPCTSTR Lpdefault,
LPTSTR lpreturnedstring,
DWORD Nsize,
LPCTSTR lpFileName
);

The meaning of each of these parameters:

The first two parameters are the same as those in writeprivateprofilestring.

Lpdefault: If the INI file does not have the field names or key names specified in the first two parameters, this value is assigned to the variable.

Lpreturnedstring: The CString object that receives the value in the INI file, that is, the destination buffer.

Nsize: The size of the destination cache.

lpFileName: Is the full INI file name.

2. How to use: Now to read the students ' information written in the previous step into the program.

CString Strstudname;
int nstudage;
GetPrivateProfileString ("Studentinfo", "name", "Default name", Strstudname.getbuffer (MAX_PATH), MAX_PATH, "c://stud// Student.ini ");

After execution Strstudname value is: "John", if the first two parameters are incorrect, the value is: "Default name."

3. Read the integer value to use another WINAPI function:

UINT Getprivateprofileint (
LPCTSTR Lpappname,
LPCTSTR Lpkeyname,
INT Ndefault,
LPCTSTR lpFileName
);

The parameters here are the same. Use the following methods:

Nstudage=getprivateprofileint ("Studentinfo", "Age", "C://stud//student.ini");
Three. Loop write multiple values, set up an existing program to save a few recently used file names, the specific procedures are as follows:

1. Write:

CString Strtemp,strtempa;
int i;
int ncount=6;
file://a total of 6 file names need to be saved
For (I=0;i {strtemp.format ("%d", I);
strtempa= filename;
file://file names can be obtained from arrays, list boxes, and so on.
:: WritePrivateProfileString ("Usefilename", "FileName" +strtemp,strtempa,
"C://usefile//usefile.ini");
}
Strtemp.format ("%d", ncount);
:: WritePrivateProfileString ("FileCount", "Count", strtemp, "C://usefile//usefile.ini");
file://writes the total number of files so that they can be read out.

2. Read out:

Ncount=::getprivateprofileint ("FileCount", "Count", 0, "C://usefile//usefile.ini");
For (I=0;i {strtemp.format ("%d", I);
strtemp= "FileName" +STRTEMP;
:: GetPrivateProfileString ("Currentini", strtemp, "Default.fil", Strtempa.getbuffer (MAX_PATH), MAX_PATH, "c:// Usefile//usefile.ini ");

FILE://uses the content in Strtempa.

}

Add Four points:
The path to the 1.INI file must be complete, the level directory preceding the file name must exist, or the write will not succeed, and the function returns a value of FALSE.
2. The path to the filename must be//, because in VC + +,//only to represent one/.
3. The INI file can also be placed in the directory where the program is located, at which time the lpFileName parameter is: ".//student.ini".

//----------------------------------------------------------------------------------
/*
Class Name: Cini
Version: v2.0
Last Updated:
v2.0
Dream Baby on February 14, 2004 Valentine's Day
Features to add advanced operations
v1.0
Dream Child on a day in 2003
General Operation complete

Class Description:
This class can be manipulated in an. ini file
*/

Document 1:

#pragma once

#include "afxTempl.h"

Class Cini
{
Private
CString M_strfilename;
Public
Cini (CString strFileName): M_strfilename (strFileName)
{
}
Public
General operations:
BOOL setfilename (LPCTSTR lpfilename); Set file name
CString getfilename (void); Get file name
BOOL SetValue (LPCTSTR lpsection, LPCTSTR Lpkey, LPCTSTR lpvalue,bool); Sets the key value, bcreate whether the segment name and the key name do not exist, are created.
CString GetValue (LPCTSTR lpsection, LPCTSTR lpkey); Gets the key value.
BOOL delsection (LPCTSTR strsection); Delete segment Name
BOOL Delkey (LPCTSTR lpsection, LPCTSTR lpkey); Delete key Name


Public
Advanced Operations:
int getsections (cstringarray& arrsection); Give all the paragraph names
int getkeyvalues (cstringarray& arrkey,cstringarray& arrvalue,lpctstr lpsection); Name and value of all keys in a paragraph

BOOL delallsections ();

};

Document 2:

#include "StdAfx.h"
#include "ini.h"

#define MAX_ALLSECTIONS 2048//All of the paragraph names
#define MAX_SECTION 260//a segment name length
#define MAX_ALLKEYS 6000//all key names
#define MAX_KEY 260//a key name length

BOOL cini::setfilename (LPCTSTR lpfilename)
{
CFile file;
CFileStatus status;

if (!file. GetStatus (Lpfilename,status))
return TRUE;

M_strfilename=lpfilename;
return FALSE;
}

CString cini::getfilename (void)
{
return m_strfilename;
}

BOOL Cini::setvalue (LPCTSTR lpsection, LPCTSTR Lpkey, LPCTSTR lpvalue,bool)
{
TCHAR Lptemp[max_path] ={0};

The following if statement indicates that if you set bcreate to False, you return True when there is no key name (indicating an error)
!*&*none-value*&!* This is a garbage character without special meaning, so scribbling is prevented by coincidence.
if (!bcreate)
{
GetPrivateProfileString (Lpsection,lpkey, "!*&*none-value*&!*", lptemp,max_path,m_strfilename);
if (strcmp (lptemp, "!*&*none-value*&!*") ==0)
return TRUE;
}

if (WritePrivateProfileString (lpsection,lpkey,lpvalue,m_strfilename))
return FALSE;
Else
return GetLastError ();
}

CString Cini::getvalue (LPCTSTR lpsection, LPCTSTR Lpkey)
{
DWORD Dvalue;
TCHAR Lpvalue[max_path] ={0};

Dvalue=getprivateprofilestring (Lpsection,lpkey, "", lpvalue,max_path,m_strfilename);
return lpvalue;
}

BOOL Cini::D elsection (LPCTSTR lpsection)
{
if (WritePrivateProfileString (lpsection,null,null,m_strfilename))
return FALSE;
Else
return GetLastError ();
}

BOOL Cini::D elkey (LPCTSTR lpsection, LPCTSTR Lpkey)
{
if (WritePrivateProfileString (lpsection,lpkey,null,m_strfilename))
return FALSE;
Else
return GetLastError ();
}


int cini::getsections (cstringarray& arrsection)
{
/*
This function is based on:
Getprivateprofilesectionnames-Gets the name of the section from the INI file
If there are two section in the INI: [SEC1] and [SEC2], then the return is ' Sec1 ', 0, ' sec2 ', 0,0, when you don't know
INI, you can use this API to get the name
*/
int i;
int ipos=0;
int imaxcount;
TCHAR chsectionnames[max_allsections]={0}; The sum of the proposed string
TCHAR chsection[max_section]={0}; Store a segment name.
Getprivateprofilesectionnames (Chsectionnames,max_allsections,m_strfilename);

The following loop, truncated to two consecutive 0
for (i=0;i<max_allsections;i++)
{
if (chsectionnames[i]==0)
if (chsectionnames[i]==chsectionnames[i+1])
Break
}

imaxcount=i+1; Need a number No. 0 element. That is, find the end of all the strings.
Arrsection.removeall ()//Empty the original array

for (i=0;i<imaxcount;i++)
{
Chsection[ipos++]=chsectionnames[i];
if (chsectionnames[i]==0)
{
Arrsection.add (chsection);
memset (chsection,0,max_section);
ipos=0;
}

}

return (int) arrsection.getsize ();
}

int cini::getkeyvalues (cstringarray& arrkey,cstringarray& arrvalue, LPCTSTR lpsection)
{
/*
This function is based on:
Getprivateprofilesection-gets all the key names and value names of a section from the INI file
If there is a segment in the INI, it has "segment 1= value 1" "Segment 2= value 2", then return is ' segment 1= value 1 ', 0, ' segment 2= value 2 ', 0,0, when you don't know
You can use this to get all the keys and values in a segment.
*/
int i;
int ipos=0;
CString strKeyValue;
int imaxcount;
TCHAR chkeynames[max_allkeys]={0}; The sum of the proposed string
TCHAR chkey[max_key]={0}; A key name that is presented

Getprivateprofilesection (Lpsection,chkeynames,max_allkeys,m_strfilename);

for (i=0;i<max_allkeys;i++)
{
if (chkeynames[i]==0)
if (chkeynames[i]==chkeynames[i+1])
Break
}

imaxcount=i+1; Need a number No. 0 element. That is, find the end of all the strings.
Arrkey.removeall ()//Empty the original array
Arrvalue.removeall ();

for (i=0;i<imaxcount;i++)
{
Chkey[ipos++]=chkeynames[i];
if (chkeynames[i]==0)
{
Strkeyvalue=chkey;
Arrkey.add (Strkeyvalue.left (strkeyvalue.find ("=")));
Arrvalue.add (Strkeyvalue.mid (strkeyvalue.find ("=") +1));
memset (Chkey,0,max_key);
ipos=0;
}

}

return (int) arrkey.getsize ();
}

BOOL Cini::D elallsections ()
{
int nsection;
CStringArray arrsection;
Nsection=getsections (arrsection);
for (int i=0;i<nsection;i++)
{
if (Delsection (Arrsection[i]))
return GetLastError ();
}
return FALSE;
}


How to use:
Cini INI ("C://a.ini");
int n;

/* Get value
TRACE ('%s ', INI. GetValue ("Paragraph 1", "Key 1"));
*/

/* Add value
Ini. SetValue ("Custom segment", "Key 1", "value");
Ini. SetValue ("Custom segment 2", "Key 1", "value", false);
*/

/* Enumerate all segment names
CStringArray arrsection;
N=ini. GetSections (arrsection);
for (int i=0;i<n;i++)
TRACE ("%s/n", Arrsection[i]);
*/

/* Enumerate all key names and values
CStringArray Arrkey,arrvalue;
N=ini. Getkeyvalues (Arrkey,arrvalue, "paragraph 1");
for (int i=0;i<n;i++)
TRACE ("Key:%s/n value:%s/n", Arrkey[i],arrvalue[i]);
*/

/* Delete key values
Ini. Delkey ("Paragraph 1", "Key 1");
*/

/* Delete Segment
Ini. Delsection ("paragraph 1");
*/

/* Delete all
Ini. Delallsections ();
*/
Related Article

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.