1.读取
读取字符
DWORD GetPrivateProfileString(
LPCTSTR lpAppName, // INI文件中的一个字段名[节名]可以有很多个节名
LPCTSTR lpKeyName, // lpAppName 下的一个键名,也就是里面具体的变量名
LPCTSTR lpDefault, // 如果lpReturnedString为空,则把个变量赋给lpReturnedString
LPTSTR lpReturnedString, // 存放键值的指针变量,用于接收INI文件中键值(数据)的接收缓冲区
DWORD nSize, // lpReturnedString的缓冲区大小
LPCTSTR lpFileName // INI文件的路径
);
读取整型值 (返回值为读到的整)
UINT GetPrivateProfileInt(
LPCTSTR lpAppName, // INI文件中的一个字段名[节名]可以有很多个节名
LPCTSTR lpKeyName, // lpAppName 下的一个键名,也就是里面具体的变量名
INT nDefault, // 如果没有找到指定的数据返回,则把个变量值赋给返回值
LPCTSTR lpFileName // INI文件的路径
);
2.写入
写入字符
BOOL WritePrivateProfileString(
LPCTSTR lpAppName, // INI文件中的一个字段名[节名]可以有很多个节名
LPCTSTR lpKeyName, // lpAppName 下的一个键名,也就是里面具体的变量名
LPCTSTR lpString, // 键值,也就是数据
LPCTSTR lpFileName // INI文件的路径
);
写入整型
读写INI文件时相对路径和绝对路径都可以,根据实际情况选择
“…\IniFileName.ini” // 这样的为相对路径
“D:\IniFileName.ini” // 这样的为绝对路径
MAX_PATH:是微软最大路径占的字节所设的宏
写入的ini文件 分为:节、键名、键值
#include <atlstr.h>
#include <Windows.h>
#include <iostream>
#include <string>
void operate_config() {
// MAX_PATH:是微软最大路径占的字节所设的宏
LPTSTR lpPath = LPTSTR(new char[MAX_PATH]);
strcpy(lpPath, ".\\IniFileName.ini");
WritePrivateProfileString("LiMing", "Sex", "Man", lpPath);
WritePrivateProfileString("LiMing", "Age", "20", lpPath);
// 写 整型要先转化为字符串再写入 std::to_string()
WritePrivateProfileString("Fangfang", "Sex", "3333", lpPath);
WritePrivateProfileString("Fangfang", "Age", "4444", lpPath);
//读取配置文件
LPTSTR LiMingSex = LPTSTR(new char[6]);
int LiMingAge;
LPTSTR FangfangSex = LPTSTR(new char[6]);
int FangfangAge;
// LPTSTR lpPath = LPTSTR(new char[MAX_PATH]);
strcpy(lpPath, ".\\IniFileName.ini");
// 读取字符串
char s[MAX_PATH];
int strTemp;
CString SexValue;
strTemp = GetPrivateProfileString(TEXT("LiMing"), TEXT("Sex"), TEXT(""), SexValue.GetBuffer(MAX_PATH), 6, lpPath); // 6(缓冲区大小)要大于值的大小 缓冲区不够大,不能容下全部信息,就返回0 (若lpApplicationName或 lpKeyName为NULL,则返回0 )
if (strTemp != NULL) {
strcpy(s, SexValue.GetBuffer(MAX_PATH));
std::string Sex(s);
std::cout << Sex << std::endl;
}
SexValue.ReleaseBuffer(); // GetBuffer函数后一定要释放(用SName.ReleaseBuffer()函数),不然后面再用到SName的其他子函数就会失灵。
// 读取整型 int
LiMingAge = GetPrivateProfileInt("LiMing", "Age", 0, lpPath);
std::cout << LiMingAge << std::endl;
// GetPrivateProfileString("Fangfang", "Sex", "", FangfangSex, 6, lpPath);
FangfangAge = GetPrivateProfileInt("Fangfang", "Sex", 0, lpPath); // // 0 如果没有找到指定的数据返回,则把个变量值赋给返回值
std::cout << FangfangAge << std::endl;
delete[] lpPath;
}
int main() {
operate_config();
system("pause");
return 0;
}