C++ 实现ini文件读写
程序员文章站
2022-04-26 22:29:52
...
实现ini配置文件读写操作,以及获取程序路径
ini格式稍微来说比较简单为:
[Tiatle]
字段1=内容
字段2=内容
内容为纯数字时,可以使用整形(int)方式读取,如果是字符串则需使用字符串(string)读取,部分代码需要用到Windows API 所以需加上windows.h头文件
使用多字节编码代码如下:
1、获取程序路径:
//获取程序路径
char* GetAppPath(char *AppPath,int nSize)
{
int i;
memset(AppPath,0,nSize);
#ifdef UNICODE
GetModuleFileNameA(NULL,AppPath,nSize);
#else
GetModuleFileName(NULL,AppPath,nSize);
#endif
for (i = strlen(AppPath) + 1; i >= 0; i --)
{
if (AppPath[i] == '\\')
{
break;
}
}
AppPath[i] = 0;
return AppPath;
}
2、读取和写入ini配置文件:
#include <iostream>
#include <windows.h>
int main()
{
char app[1024] = {0};
GetAppPath(app,sizeof(app));
char filepath[1024] = {0};
sprintf_s(filepath,"%s\\ConfigDevice.ini",app);
char buf[1024] = "";
char szTitle[] = "Title";
//读取整形数据
#ifdef UNICODE
int Number = GetPrivateProfileIntA(szTitle,"DeviceIndex",0,filepath);
//读取字符串数据
GetPrivateProfileStringA(szTitle,"DeviceName","TestData",buf,sizeof(buf),filepath);
#else
int Number = GetPrivateProfileInt(szTitle,"DeviceIndex",0,filepath);
GetPrivateProfileString(szTitle,"DeviceName","TestData",buf,sizeof(buf),filepath);
#endif
//写入整形数据
char szTmp[64];
sprintf(szTmp,"%d",Number);
#ifdef UNICODE
WritePrivateProfileStringA(szTitle,"DeviceIndex",szTmp,filepath);
//直接写入字符串数据
WritePrivateProfileStringA(szTitle,"DeviceName","WriteData2",filepath);
#else
WritePrivateProfileString(szTitle,"DeviceIndex",szTmp,filepath);
WritePrivateProfileString(szTitle,"DeviceName","WriteData",filepath);
#endif
}
程序运行结果:
在运行目录下生成ConfigDevice.ini文件,内容是程序写入的
使用Unicode字符编码
#include <iostream>
#include <windows.h>
LPWSTR toUnicode(const char* _str)
{
LPWSTR _ret;
int _len = strlen(_str) * 2;
_ret = new WCHAR[_len];
MultiByteToWideChar(CP_ACP, 0, _str, -1, _ret, _len);
return _ret;
}
//获取程序路径
wchar_t* GetAppPath(wchar_t *AppPath,int nSize)
{
int i;
memset(AppPath,0,nSize);
GetModuleFileName(NULL,AppPath,nSize);
for (i = wcslen(AppPath) + 1; i >= 0; i --)
{
if (AppPath[i] == '\\')
{
break;
}
}
AppPath[i] = 0;
return AppPath;
}
int main()
{
wchar_t app[1024] = {0};
GetAppPath(app,sizeof(app));
wchar_t filepath[512] = {0};
wsprintf(filepath,toUnicode("%s\\ConfigDevice.ini"),app);
wchar_t buf[2048] = {0};
wchar_t szTitle[10] = {0};
//memcpy(szTitle,toUnicode("Title"),sizeof("Title"));
wcsncpy_s(szTitle,toUnicode("Title"),sizeof("Title"));
//读取整形数据
int Number = GetPrivateProfileInt(szTitle,toUnicode("DeviceIndex"),0,filepath);
//读取字符串数据
GetPrivateProfileString(szTitle,toUnicode("DeviceName"),toUnicode(""),buf,sizeof(buf),filepath);
//写入整形数据
char szTmp[64];
sprintf(szTmp,"%d",Number);
WritePrivateProfileString(szTitle,toUnicode("DeviceIndex"),toUnicode(szTmp),filepath);
//直接写入字符串数据
WritePrivateProfileString(szTitle,toUnicode("DeviceName"),toUnicode("WriteData"),filepath);
wprintf(toUnicode("%s\n"),buf);
}
上一篇: 安装GraphViz以供python调用
下一篇: Java内存溢出OOM使用Mat分析