Tuesday, December 30, 2008

[VC++] Reading and Writing INI files

INI files are simple text files with a basic structure. The name "INI file" comes from the file name extension usually used, ".INI", that stands for "initialization". Sometimes, files using the INI file format will use a different extension, such as ".CFG", ".conf", or ".TXT".
INI files contain one or more sections. Each section begins with a section name, which is followed by zero or more entries. An entry associates a keyname with a value. The general format is:
[section]
keyname=value

So in Your application if you might be in need for saving some configuration and using it then you can prefer .INI files. Here is the code which shall explain how to read and write INI files,

Writing Section Data
Code
// Writing section with one key
if(::WritePrivateProfileSection("Section1", "key1=Value1\0", "C:\\Test.ini"))
{
// Success
}
// Writing section with more than one key
if(::WritePrivateProfileSection("Section2", "key1=Value1\0key2=Value2\0", "C:\\Test.ini"))
{
// Success
}
C:\Test.ini on executing above code
[Section1]
key1=Value1
[Section2]
key1=Value1
key2=Value2

Writing Key & value
Code
// Modify the string value of a given key
if( ::WritePrivateProfileString("Section1", "key1", "NewValue1", "C:\\Test.ini"))
{
// Success
}
// Write new key and string value
if( ::WritePrivateProfileString("Section1", "key2", "Value2", "C:\\Test.ini"))
{
// Success
}
C:\Test.ini on executing above code
[Section1]
key1=NewValue1
key2=Value2
[Section2]
key1=Value1
key2=Value2

Remove Key
Code
// Remove the key by writing null value
if( ::WritePrivateProfileString("Section2", "key2", 0, "C:\\Test.ini"))
{
// Success
}
C:\Test.ini on executing above code
[Section1]
key1=NewValue1
key2=Value2
[Section2]
key1=Value1

Write Number
Code
CString csNum;
csNum.Format( "%d", 1000 );
// Write new key with number value
if( ::WritePrivateProfileString("Section1", "key3", csNum, "C:\\Test.ini"))
{
// Success
}
C:\Test.ini on executing above code
[Section1]
key1=NewValue1
key2=Value2
key3=1000
[Section2]
key1=Value1

Read String
Code
char *szValue = new char[MAX_PATH];
memset( szValue, 0, MAX_PATH );
// Read string from the INI file
if(::GetPrivateProfileString( "Section1", "Key1", 0, szValue, MAX_PATH, "C:\\Test.ini" ))
{
MessageBox( szValue );
}
Output
MessageBox will be shown with 'NewValue1'

Read Number
Code
// Read number from the INI file
int nNum = ::GetPrivateProfileInt("Section1", "Key3", 0, "C:\\Test.ini");
CString csNum;csNum.Format( "%d", nNum );
MessageBox( csNum );
Output
MessageBox will be shown with '1000'

1 comment:

ponmudi said...

code looking good, but i am not able to write new section with key,value pair in an empty .ini file.
i am using writeprivateprofilesection()
i dont know why, can anyone help me?
thanks.