在VC++中读写INI文件写ini文件 在ini 文件里的信息是这样的: [successcompath]
如:WritePrivateProfileString(_T("FileCount"),_T("Count"),_T("lijiandong"),_T("d://usefile.ini")); 在 d://usefile.ini 里是这样的
[FileCount] //读 从successcompath里读取信息到repath里面 如果读取不到任何信息 就读取"C://"到repath里面
在我们写的程序当中,总有一些配置信息需要保存下来,以便完成程序的功能,最简单的办法就是将这些信息写入INI文件中,程序初始化时再读入.具体应用如下: 一.将信息写入.INI文件中. 1.所用的WINAPI函数原型为:
其中各参数的意义: LPCTSTR lpAppName 是INI文件中的一个字段名. LPCTSTR lpKeyName 是lpAppName下的一个键名,通俗讲就是变量名. LPCTSTR lpString 是键值,也就是变量的值,不过必须为LPCTSTR型或CString型的. LPCTSTR lpFileName 是完整的INI文件名. 2.具体使用方法:设现有一名学生,需把他的姓名和年龄写入 c:/stud/student.ini 文件中.
此时c:/stud/student.ini文件中的内容如下: [StudentInfo] Name=张三 3.要将学生的年龄保存下来,只需将整型的值变为字符型即可:
二.将信息从INI文件中读入程序中的变量. 1.所用的WINAPI函数原型为:
其中各参数的意义: 前二个参数与 WritePrivateProfileString中的意义一样. lpDefault : 如果INI文件中没有前两个参数指定的字段名或键名,则将此值赋给变量. lpReturnedString : 接收INI文件中的值的CString对象,即目的缓存器. nSize : 目的缓存器的大小. lpFileName : 是完整的INI文件名. 2.具体使用方法:现要将上一步中写入的学生的信息读入程序中.
执行后 strStudName 的值为:"张三",若前两个参数有误,其值为:"默认姓名". 3.读入整型值要用另一个WINAPI函数:
这里的参数意义与上相同.使用方法如下:
三.循环写入多个值,设现有一程序,要将最近使用的几个文件名保存下来,具体程序如下: 1.写入:
2.读出:
补充四点: 1.INI文件的路径必须完整,文件名前面的各级目录必须存在,否则写入不成功,该函数返回 FALSE 值. 2.文件名的路径中必须为 // ,因为在VC++中, // 才表示一个 / . 3.也可将INI文件放在程序所在目录,此时 lpFileName 参数为: ".//student.ini". 4.从网页中粘贴源代码时,最好先粘贴至记事本中,再往VC中粘贴,否则易造成编译错误,开始时我也十分不解,好好的代码怎么就不对呢?后来才找到这个方法.还有一些代码中使用了全角字符如:<,\等,也会 造成编译错误. |
example:
//写ini文件
CString strroot1;
strroot.Empty();
CString curstr;//当前路径
int curi;
curi=d_combopath.GetCurSel();//获取当前索引值
d_combopath.GetLBText(curi,curstr);// 获取combox内容 存放在curstr中
strroot1.Append(curstr);
CString index;
int idx;
idx=0;
index.Format(_T("%d"),idx);
::WritePrivateProfileString(_T("successcompath"),
index,strroot1,_T(".//ex1.ini"));