MFC 读写配置文件——ini文件

1、写ini文件

把student.ini 放到C盘根目录下,路径也可以在程序里的两个函数调整

BOOL WritePrivateProfileString(

  LPCTSTR lpAppName,

  LPCTSTR lpKeyName,

  LPCTSTR lpString,

  LPCTSTR lpFileName

  );

  其中各参数的意义

  LPCTSTR lpAppName 是INI文件中的一个字段名.

  LPCTSTR lpKeyName 是lpAppName下的一个键名,通俗讲就是变量名.

  LPCTSTR lpString 是键值,也就是变量的值,不过必须为LPCTSTR型或CString型的.

LPCTSTR lpFileName 是完整的INI文件名.

2、读ini文件

读整型

 UINT GetPrivateProfileInt(

  LPCTSTR lpAppName,

  LPCTSTR lpKeyName,

  INT nDefault,

  LPCTSTR lpFileName

  );  nStudAge=GetPrivateProfileInt("StudentInfo","Age",10,"c:\\stud\\student.ini");

参数 类型及说明

  lpApplicationName String,指定在其中查找条目的小节。注意这个字串是不区分大小写的

  lpKeyName String,欲获取的设置项或条目。这个支持不区分大小写

  nDefault Long,指定条目未找到时返回的默认值

  lpFileName String,初始化文件的名字。如果没有指定完整的路径名,windows就会在Windows目录中搜索文件

读字符串

DWORD GetPrivateProfileString(

  LPCTSTR lpAppName,

  LPCTSTR lpKeyName,

  LPCTSTR lpDefault,

  LPTSTR lpReturnedString,

  DWORD nSize,

  LPCTSTR lpFileName

  );

  其中各参数的意义

  前二个参数与 WritePrivateProfileString中的意义一样.

  lpDefault : 如果INI文件中没有前两个参数指定的字段名或键名,则将此值赋给变量.

  lpReturnedString : 接收INI文件中的值的CString对象,即目的缓存器.

  nSize : 目的缓存器的大小.

  lpFileName : 是完整的INI文件名.

void CIniRWDlg::OnBtnwini()                  //响应WriteIniFile按钮的事件

{

       // TODO: Add your control notification handler code here

       CString strName,strTemp;

       int nAge;

       strName="张三";                        //写入的键

       nAge=12;                                  //写入的值

       ::WritePrivateProfileString("StudentInfo","Name",strName,"c:\\student.ini");

      

       strTemp.Format("%d",nAge);

       ::WritePrivateProfileString("StudentInfo","Age",strTemp,"c:\\student.ini");

}

 

void CIniRWDlg::OnBtnrini()                    //响应ReadIniFile按钮的事件

{

       // TODO: Add your control notification handler code here

      

       CString strStudName;

       CString showIni;

       int nStudAge;

       GetPrivateProfileString("StudentInfo","Name","默认姓名",strStudName.GetBuffer(MAX_PATH),MAX_PATH,"c:\\student.ini");

 

       nStudAge=GetPrivateProfileInt("StudentInfo","Age",10,"c:\\student.ini");

      

       showIni.Format("student.ini\n%s%c%d",strStudName,':',nStudAge);        //字符串拼接

       GetDlgItem(IDC_SHOWINI)->SetWindowText(showIni);                       //显示到静态文本框中,该静态文本框的默认ID 为 ID_STATIC 改成了 IDC_SHOWINI.

}


原文地址:https://www.cnblogs.com/jinsedemaitian/p/5589187.html