1. 与 .ini 文件相关的 API 有两类:
1)操作系统配置文件 Win.ini 的函数
GetProfileSection
GetProfileString
GetProfileInt
WriteProfileSection
WriteProfileString
2)操作用户自定义配置文件 PrivateProfile.ini 的函数
GetPrivateProfileSectionNames
GetPrivateProfileSection
GetPrivateProfileString
GetPrivateProfileInt
GetPrivateProfileStruct
WritePrivateProfileSection
WritePrivateProfileString
WritePrivateProfileStruct
2. 操作用户自定义配置文件相关 API 的示例代码
#include <Windows.h>
#include <tchar.h>
#include <strsafe.h>
#pragma comment(lib, "strsafe.lib")
#define INI_FILE_NAME _T("ini_test.ini")
TCHAR gIniFileFullPath[MAX_PATH] = {_T('\0')};
int main()
{
DWORD dwRet = 0;
BOOL bRet = FALSE;
// 获取 ini 文件全路径
dwRet = ::GetModuleFileName(NULL, gIniFileFullPath, MAX_PATH);
if (0UL == dwRet)
{
_ftprintf(stderr, _T("Error: Error occurs in calling GetModuleFileName, ")
_T("error code is %lu.\n"),
::GetLastError());
return -1;
}
if (MAX_PATH == dwRet && ERROR_INSUFFICIENT_BUFFER == ::GetLastError())
{
_ftprintf(stderr, _T("Error: The buffer is too small to hold the module name.\n"));
return -1;
}
_tprintf(_T("The full path for the current module is: \n\t%s\n"), gIniFileFullPath);
DWORD dwLoopIdx = dwRet - 1;
while (gIniFileFullPath[dwLoopIdx] != _T('\\'))
{
--dwLoopIdx;
}
::StringCchCopy(gIniFileFullPath + (dwLoopIdx + 1), MAX_PATH - (dwLoopIdx + 1), INI_FILE_NAME);
_tprintf(_T("The full path for %s is: \n\t%s\n"), INI_FILE_NAME, gIniFileFullPath);
// ---------------------------------------------- WritePrivateProfileSection
// 注: 如果 gIniFileFullPath 表示的 .ini 文件不存在, 会先创建一个.
TCHAR szInsertedKeyValuePair[1024] = {_T('\0')};
#if defined(_UNICODE) || defined(UNICODE)
wchar_t* dest = NULL;
wchar_t* src = NULL;
size_t count = 0;
dest = szInsertedKeyValuePair;
src = L"Key11=defaultValue11";
count = wcslen(L"Key11=defaultValue11");
wmemcpy(dest, src, count);
dest += count;
src = L"\0";
count = 1;
wmemcpy(dest, src, count);
dest += count;
src = L"Key12=defaultValue12";
count = wcslen(L"Key12=defaultValue12");
wmemcpy(dest, src, count);
dest += count;
src = L"\0";
count = 1;
wmemcpy(dest, src, count);
dest += count;
src = L"Key13=defaultValue13";
count = w