C++ ini 文件的读写

https://bbs.csdn.net/topics/391920522

先 参考 之前的一个博文

配置文件中经常用到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);

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

实际应用的例子:

(1) 读ini 内容:

这个是string 的读入:

LPTSTR lpTexts = new TCHAR(9);

GetPrivateProfileString(TEXT("Threshold"), TEXT("edge_Threshold"), TEXT("0.19"), lpTexts, 8, TEXT("..\\specValue.ini"));

string str = CT2A(lpTexts);

这个是 int 的读入:



(2) 写 ini 内容:

WritePrivateProfileString(_T("RegionSetup"), TEXT("in_Size"), str2lpt(in_Size), TEXT("..\\specValue.ini"));

其中的一个子函数用于  string 转 LPTSTR:

LPTSTR str2lpt(string v) {
CString ctmp = v.c_str();
LPTSTR lptstr_tmp = new TCHAR(ctmp.GetLength() + 1);
lstrcpy(lptstr_tmp, ctmp);
return lptstr_tmp;
}



猜你喜欢

转载自blog.csdn.net/guosongye/article/details/80208328