Microsoft Windows2000、WindowsXP和其它的最近发布的Microsoft操作系统版本,一般不会用system.ini和win.ini文件。出于兼容性考虑,它们用一个叫做IniFileMapping的功能。IniFileMapping将所有目录中的.ini文件注册入注册表的.ini文件键值中。当你运行一个程序,一般会先读取其中的.ini文件的参数,Windows会先检查注册表键HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows NT/CurrentVersion/IniFileMapping中的.ini映射。如果找到了,Windows就会从其中的键值中的设置参数代替该.ini文件。
MSDN中有用WritePrivateProfileString写注册表的例子,不过有点小小的错误
在程序中如果要使用WritePrivateProfileString写注册表,可通过在IniFileMapping中写入键值,这样对相关INI的操作转为对注册表的操作。例子如下
如果我们希望按INI格式写入
[Section1] FirstKey = It all worked out okay. SecondKey = By golly, it works. ThirdKey = Another test.
代码实现如下:
#include <stdio.h>
#include <windows.h>
int main()
{
CHAR inBuf[80];
HKEY hKey1, hKey2;
DWORD dwDisposition;
LONG lRetCode;
CHAR szData[] = "USR:App Name//Section1";
// Create the .ini file key.
lRetCode = RegCreateKeyEx ( HKEY_LOCAL_MACHINE,
"SOFTWARE//Microsoft//Windows NT//CurrentVersion//IniFileMapping//appname.ini",
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_WRITE,
NULL,
&hKey1,
&dwDisposition);
if (lRetCode != ERROR_SUCCESS)
{
printf ("Error in creating appname.ini key/n");
return (0) ;
}
// Set a section value
lRetCode = RegSetValueEx ( hKey1,
"Section1",
0,
REG_SZ,
(BYTE *)szData, //MSDN这里有小错误
sizeof(szData);
if (lRetCode != ERROR_SUCCESS)
{
printf ("Error in setting Section1 value/n");
// Close the key
lRetCode = RegCloseKey( hKey1 );
if( lRetCode != ERROR_SUCCESS )
{
printf("Error in RegCloseKey/n");
return (0) ;
}
}
// Create an App Name key
lRetCode = RegCreateKeyEx ( HKEY_CURRENT_USER,
"App Name",
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_WRITE,
NULL,
&hKey2,
&dwDisposition);
if (lRetCode != ERROR_SUCCESS)
{
printf ("Error in creating App Name key/n");
// Close the key
lRetCode = RegCloseKey( hKey2 );
if( lRetCode != ERROR_SUCCESS )
{
printf("Error in RegCloseKey/n");
return (0) ;
}
}
// Force the system to read the mapping into shared memory
// so that future invocations of the application will see it
// without the user having to reboot the system
//这句是触发映射
WritePrivateProfileStringW( NULL, NULL, NULL, L"appname.ini" );
// Write some added values
//上面部分完成了对INI文件的映射
//这样写入时,会写入HKEY_CURRENT_USER/App Name项下
//如果不产生映射,则在本文件目录下产生appname.ini
WritePrivateProfileString ("Section1",
"FirstKey",
"It all worked out okay.",
"appname.ini");
WritePrivateProfileString ("Section1",
"SecondKey",
"By golly, it works.",
"appname.ini");
WritePrivateProfileSection ("Section1",
"ThirdKey = Another Test.",
"appname.ini");
// Test
GetPrivateProfileString ("Section1",
"FirstKey",
"Bogus Value: Get didn't work",
inBuf,
80,
"appname.ini");
printf ("%s", inBuf);
// Close the keys
lRetCode = RegCloseKey( hKey1 );
if( lRetCode != ERROR_SUCCESS )
{
printf("Error in RegCloseKey/n");
return(0);
}
lRetCode = RegCloseKey( hKey2 );
if( lRetCode != ERROR_SUCCESS )
{
printf("Error in RegCloseKey/n");
return(0);
}
return(1);
}