一、将信息写入.ini文件中.
所用的WINAPI函数原型为:
- BOOL WritePrivateProfileStringA(
- LPCTSTR lpAppName,
- LPCTSTR lpKeyName,
- LPCTSTR lpString,
- LPCTSTR lpFileName
- );
其中各参数的意义
:
- LPCTSTR lpAppName 是INI文件中的一个字段名.
- LPCTSTR lpKeyName 是lpAppName下的一个键名,通俗讲就是变量名.
- LPCTSTR lpString 是键值,也就是变量的值,不过必须为LPCTSTR型或CString型的.
- LPCTSTR lpFileName 是完整的INI文件名.
1. 设现有一名学生,需把他的姓名和年龄写入程序所在目录的student.ini文件中.
1).
- LPCTSTR strName;
- strName = (LPCTSTR)"Sunny";
- ::WritePrivateProfileString(L"StudentInfo", L"Name", strName, L".\\student.ini");
这种方式在ini文件中会才出现中文乱码
2).
- ::WritePrivateProfileString(L"StudentInfo", L"Name", L"Sunny", L".\\student.ini");
这种方式在ini文件中不会出现中文乱码,但是第3个参数,键值是硬编码,多数情况下不会这样写
3).
- string strName;
- strName = "Sunny";
- ::WritePrivateProfileStringA("StudentInfo", "Name", strName.c_str(), ".\\student.ini");
这种方式在ini文件中也不会出现中文乱码,是一种比较好的解决方法
4).
- char strName[MAX_PATH] = "Sunny";
- ::WritePrivateProfileStringA("StudentInfo", "Name", strName, ".\\student.ini");
同上
2. 要将学生的年龄保存下来,只需将整型的值变为字符型即可:
- char chTemp[4];
- int nAge = 22;
- itoa(nAge, chTemp, 10);
- ::WritePrivateProfileStringA("StudentInfo", "Age", chTemp, ".\\student.ini");
写出之后,程序所在目录的student.ini文件的内容如下:
[StudentInfo]
Name=Sunny
Age=22
二、将信息从INI文件中读入程序中的变量.
1、将ini文件中的学生的姓名读入程序中
所用的WINAPI函数原型为:
- DWORD GetPrivateProfileStringA(
- LPCTSTR lpAppName,
- LPCTSTR lpKeyName,
- LPCTSTR lpDefault,
- LPTSTR lpReturnedString,
- DWORD nSize,
- LPCTSTR lpFileName
- );
其中各参数的意义
:
前二个参数与
WritePrivateProfileString
中的意义一样
.
lpDefault :
如果
INI
文件中没有前两个参数指定的字段名或键名
,
则将此值赋给变量
.
lpReturnedString :
接收
INI
文件中的值的对象
(LPCTSTR
型或
CString
型
),
即目的缓存器
.
nSize :
目的缓存器的大小
.
lpFileName :
是完整的
INI
文件名
使用如下:
- char chStudentName[MAX_PATH];
- GetPrivateProfileStringA("StudentInfo", "Name", "默认姓名", chStudentName, MAX_PATH, ".\\student.ini");
执行后 strStudentName 的值为:"Sunny"; 若前两个参数有误,其值为:"默认姓名".
2. 读入整型值要用另一个WINAPI函数:
- UINT GetPrivateProfileInt(
- LPCTSTR lpAppName,
- LPCTSTR lpKeyName,
- INT nDefault,
- LPCTSTR lpFileName
- );
使用如下:
这里的参数意义与上相同.
- int nStudentAge;
- nStudentAge = GetPrivateProfileIntA("StudentInfo", "Age", 20, ".\\student.ini");
执行后 nStudentAge 的值为:22; 若前两个参数有误,其值为:20.
三、几点说明:
1. ini文件的路径必须完整,文件名前面的各级目录必须存在,否则写入不成功,该函数返回 FALSE值.例如:lpFileName 参数为: ".c:\\usefile\\usefile.ini";也可将ini文件放在程序所在目录,此时 lpFileName 参数为: ".\\student.ini",实例即写到程序所在目录下。
2. MFC环境下的ini文件读写,网上可以找到很多例子,本例子针对Win32环境下的ini文件读取操作。