记录一下,读取.ini配置文件的方法。
实际中,一般先获得当前程序所在路径(或者放在特定的配置文件目录)
GetModuleFileName
解释下这句:strrchr(cfgpath, '\\')[0] = '\0';
strrchr(cfgpath, '\\')返回路径中'\'最后出现的位置,strrchr(cfgpath, '\\')[0]则把该位置改为'\0'。之后strcat后,就得到了配置文件的绝对地址。
GetPrivateProfileStringA(这里是字符串,还有其他类型的)就是得到配置文件相应值得函数了,一定要是绝对路径。
char cfgpath[MAX_PATH];
int bDenoise = 0;
if (GetModuleFileNameA(NULL, cfgpath, MAX_PATH) > 0)
{
strrchr(cfgpath, '\\')[0] = '\0';
strcat(cfgpath, "\\config.ini");
char tmp[8];
GetPrivateProfileStringA("denoise", "denoise", "0", tmp, 8, cfgpath);
bDenoise = atoi(tmp);
}
还有一种宽字符的写法:
TCHAR iniFullPath[MAX_PATH];
if (GetModuleFileName(NULL, iniFullPath, MAX_PATH) > 0)
{
(_tcsrchr(iniFullPath, _T('\\')))[1] = 0;
wstring strPath = iniFullPath;
strPath = strPath + _T("config.ini");
bDenoise = GetPrivateProfileInt(L"denoise", L"denoise", 0, strPath.c_str());
}