本帖最后由 娃娃鱼 于 2020-5-4 16:36 编辑
C++对ini文件的读写操作
配置文件中经常用到ini文件,在VC中其函数分别为:
写入.ini文件: BOOL WritePrivateProfileString( LPCTSTR lpAppName, // INI文件中的一个字段名[节名]可以有很多个节名
LPCTSTR lpKeyName, // lpAppName 下的一个键名,也就是里面具体的变量名
LPCTSTR lpString, // 键值,也就是数据
LPCTSTR lpFileName // INI文件的路径 );
读取.ini文件: 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文件的路径
- );
复制代码 读写INI文件时相对路径和绝对路径都可以,根据实际情况选择- "..//IniFileName.ini" // 这样的为相对路径
- "D://IniFileName.ini" // 这样的为绝对路径
复制代码 MAX_PATH:是微软最大路径占的字节所设的宏
例子:
写INI文件:- LPTSTR lpPath = new char[MAX_PATH];
- strcpy(lpPath, "D://IniFileName.ini");
- WritePrivateProfileString("LiMing", "Sex", "Man", lpPath);
- WritePrivateProfileString("LiMing", "Age", "20", lpPath);
- WritePrivateProfileString("Fangfang", "Sex", "Woman", lpPath);
- WritePrivateProfileString("Fangfang", "Age", "21", lpPath);
- delete [] lpPath;
复制代码 INI文件如下:- [LiMing]
- Sex=Man
- Age=20
- [Fangfang]
- Sex=Woman
- Age=21
复制代码 读INI文件:- LPTSTR lpPath = new char[MAX_PATH];
- LPTSTR LiMingSex = new char[6];
- int LiMingAge;
- LPTSTR FangfangSex = new char[6];
- int FangfangAge;
- strcpy(lpPath, "..//IniFileName.ini");
- GetPrivateProfileString("LiMing", "Sex", "", LiMingSex, 6, lpPath);
- LiMingAge = GetPrivateProfileInt("LiMing", "Age", 0, lpPath);
- GetPrivateProfileString("Fangfang", "Sex", "", FangfangSex, 6, lpPath);
- FangfangAge = GetPrivateProfileInt("Fangfang", "Age", 0, lpPath);
- delete [] lpPath;
复制代码
|