C++ | 读写配置文件

182 阅读1分钟

「这是我参与11月更文挑战的第7天,活动详情查看:2021最后一次更文挑战」。

读取配置文件:

1.定义文件路径:

CString strFilePath=_T(".\FILES\config.ini");

2.判断文件是否存在:

if (!PathFileExists(strFilePath)){return;}

3.读取数据:

int nkeyValue = GetPrivateProfileInt(_T("AppName"),_T("KeyName"),TRUE,strFilePath);//(AppName, KeyName, 默认值, 文件名)

Cstring strKeyValue = ""; GetPrivateProfileString(_T("AppName"),_T("KeyName"),_T(""),strKeyValue .GetBuffer(MAX_PATH),MAX_PATH,strFilePath); //(AppName, KeyName, 默认值,返回值,大小,文件名)

strKeyValue .ReleaseBuffer(); //千万不能少这句话

写入配置文件:

1.定义文件路径:

CString strFilePath=_T(".\FILES\config.ini");

2.判断文件是否存在:

if (!PathFileExists(strFilePath)){return;}

3.写入数据:

Cstring strKeyValue = _T("keyname");

WritePrivateProfileString(_T("AppName"),_T("KeyName"),strKeyValue ,strFilePath); //(AppName, KeyName, 写入值, 文件名)