【转载】C++针对ini配置文件读写大全

时间:2014-10-08 15:51:45   收藏:0   阅读:276

http://blog.csdn.net/hgy413/article/details/6666374#

ini文件(Initialization file),这种类型的文件中通常存放的是一个程序的初始化信息。ini文件由若干个节(Section)组成,每个Section由若干键(Key)组成,每个Key可以赋相应的值。读写ini文件实际上就是读写某个的Section中相应的Key的值,而这只要借助几个函数即可完成。

1. 把信息写入系统的win.ini文件

BOOL WriteProfileString(
LPCTSTR lpAppName,     // 节的名字,是一个以0结束的字符串
LPCTSTR lpKeyName,      // 键的名字,是一个以0结束的字符串。若为NULL,则删除整个节
LPCTSTR lpString             // 键的值,是一个以0结束的字符串。若为NULL,则删除对应的键
)

2、从系统的win.ini文件中读取信息

DWORD GetProfileString(
LPCTSTR lpAppName,            // 节名
LPCTSTR lpKeyName,             // 键名,读取该键的值
LPCTSTR lpDefault,                // 若指定的键不存在,该值作为读取的默认值
LPTSTR lpReturnedString,     // 一个指向缓冲区的指针,接收读取的字符串
DWORD nSize                          // 指定lpReturnedString指向的缓冲区的大小
)
UINT GetProfileInt(
LPCTSTR lpAppName,            // 同上
LPCTSTR lpKeyName,             // 同上
INT nDefault                             // 若指定的键名不存在,该值作为读取的默认值
)

3.写入读取自己的ini

简单的INI例子:

[Service]
Name=AutoRun  Helper
Description=200
ApplicationRootKey64=Software\Wow6432Node\Sepang\AutoRun Modem
[Registry]
ServiceRootKey=Software\AutoRun Modem Service
ApplicationRootKey=Software\Sepang\AutoRun Modem
ApplicationRootKey64=Software\Wow6432Node\Sepang\AutoRun Modem

下面示例显示它是如何生成的:

void XXXXX::OnBnClickedWriteIniBtn()
{
    // ----------------------------------------
    // 模拟写入一个config.ini
    // ----------------------------------------

    // 得到exe执行路径.
    TCHAR tcExePath[MAX_PATH] = {0};
    ::GetModuleFileName(NULL, tcExePath, MAX_PATH);
    // 设置ini路径到exe同一目录下
#ifndef CONFIG_FILE
#define CONFIG_FILE        (TEXT("Config1.ini"))
#endif
    //_tcsrchr() 反向搜索获得最后一个‘\\‘的位置,并返回该位置的指针
    TCHAR *pFind = _tcsrchr(tcExePath, \\);
    if (pFind == NULL)
    {
        return;
    }
    *pFind = \0;
    
    CString szIniPath = tcExePath;
    szIniPath += "\\";
    szIniPath += CONFIG_FILE;

    //--------------------------------------------------------
    //BOOL WritePrivateProfileString(
    //                              LPCTSTR lpAppName,      //节的名字,是一个以0结束的字符串
    //                                LPCTSTR lpKeyName,      //键的名字,是一个以0结束的字符串。若为NULL,则删除整个节
    //                                LPCTSTR lpString,       //键的值,是一个以0结束的字符串。若为NULL,则删除对应的键
    //                                LPCTSTR lpFileName      //要写入的文件的文件名。若该ini文件与程序在同一个目录下,
    //                              )                          也可使用相对路径,否则需要给出绝度路径。
    //如果Ini不存在,它会自动在szIniPath上创建此INI文件.再执行写入.                           
    ::WritePrivateProfileString(TEXT("Service"), TEXT("Name"), TEXT("AutoRun  Helper"), szIniPath);
    ::WritePrivateProfileString(TEXT("Service"), TEXT("Description"), TEXT("200"), szIniPath);

    ::WritePrivateProfileString(TEXT("Registry"), TEXT("ServiceRootKey"), TEXT("Software\\AutoRun Modem Service"), szIniPath);
    ::WritePrivateProfileString(TEXT("Registry"), TEXT("ApplicationRootKey"), TEXT("Software\\Sepang\\AutoRun Modem"), szIniPath);
    ::WritePrivateProfileString(TEXT("Registry"), TEXT("ApplicationRootKey64"), TEXT("Software\\Wow6432Node\\Sepang\\AutoRun Modem"), szIniPath);

    //这个说明不同节之中可以存在完全相同的键.
    ::WritePrivateProfileString(TEXT("Service"), TEXT("ApplicationRootKey64"), TEXT("Software\\Wow6432Node\\Sepang\\AutoRun Modem"), szIniPath);

    
    //下面执行读取 ----------------------------------
    if (!::PathFileExists(szIniPath))
    {
        return;
    }

    TCHAR szKeyValue[MAX_PATH] = {0};
    int nValue = 0;

    //--------------------------------------------------------
    //DWORD GetPrivateProfileString(
    //                              LPCTSTR lpAppName,            // 节名
    //                              LPCTSTR lpKeyName,            // 键名,读取该键的值
    //                               LPCTSTR lpDefault,            // 若指定的键不存在,该值作为读取的默认值
    //                              LPTSTR lpReturnedString,      // 一个指向缓冲区的指针,接收读取的字符串
    //                               DWORD nSize,                  // 指定lpReturnedString指向的缓冲区的大小
    //                                 LPCTSTR lpFileName            // 读取信息的文件名。若该ini文件与程序在同一个目录下,
    //                                                                也可使用相对路径,否则需要给出绝度路径
    //UINT GetPrivateProfileInt(
    //                              LPCTSTR lpAppName,            // 节名
    //                                 LPCTSTR lpKeyName,            // 键名,读取该键的值
    //                              INT nDefault,                 // 若指定的键名不存在,该值作为读取的默认值
    //                               LPCTSTR lpFileName            // 同上
    //
    //--------------------------------------------------------

    ::GetPrivateProfileString(TEXT("Service"), TEXT("Name"), NULL, szKeyValue, MAX_PATH, szIniPath);
    nValue = ::GetPrivateProfileInt(TEXT("Service"), TEXT("Description"), 0, szIniPath);


}

四、如何判断一个ini文件中有多少个节

要判断一个ini文件中有多少个节,最简单的办法就是将所有的节名都找出来,然后统计节名的个数。而要将所有的节名找出来,使用GetPrivateProfileSectionNames函数就可以了,其原型如下:

DWORDGetPrivateProfileSectionNames(

LPTSTR lpszReturnBuffer,     // 指向一个缓冲区,用来保存返回的所有节名。

DWORD nSize,                         // 参数lpszReturnBuffer的大小。

LPCTSTR lpFileName               // 文件名,若该ini文件与程序在同一个目录下,

// 也可使用相对路径,否则需要给出绝度路径。

)

下面的是用来统计一个ini文件中共有多少个节的函数,当然,如果需要同时找到每个节中的各个键及其值,根据找到节名就可以很容易的得到了。

/* 统计共有多少个节

节名的分离方法:若chSectionNames数组的第一字符是‘\0‘字符,则表明有0个节。

否则,从chSectionNames数组的第一个字符开始,顺序往后找,直到找到一个‘\0‘字符,

若该字符的后继字符不是‘\0‘字符,则表明前面的字符组成一个节名。

若连续找到两个‘\0‘字符,则统计结束。 */

TCHAR chSectionNames[2048] = {0};  
    TCHAR *pSectionName;   // 保存找到的某个节名字符串的首地址。
    int j=0;               // j用来保存下一个节名字符串的首地址相对于当前i的位置偏移量。
    int count = 0;         // 统计节的个数。

    ::GetPrivateProfileSectionNames(chSectionNames, 2048, szIniPath);
    for (i=0; i<2048; i++, j++)
    {
        if (chSectionNames[0] == \0)
        {
            break;       // 如果第一个字符就是0,则说明ini中一个节也没有。
        }

        if (chSectionNames[i] == \0)
        {
            // 找到一个’\0’,则说明从这个字符往前,减掉j个偏移量,就是一个节名的首地址。
            pSectionName = &chSectionNames[i-j]; 
            // 找到一个节名后,j的值要还原,以统计下一个节名地址的偏移量。
            // 赋成-1是因为节名字符串的最后一个字符’\0’是终止符,不能作为节名的一部分。
            j = -1;

            // 在获取节名的时候可以获取该节中键的值,前提是我们知道该节中有哪些键。
            AfxMessageBox(pSectionName);   // 把找到的显示出来。

            if (chSectionNames[i+1] == 0)   //is 0 or ‘\0’?
            {
                break;  // 当两个相邻的字符都是0时,则所有的节名都已找到,循环终止。
            }
        }
    }

在VC程序中利用系统提供的GetPrivateProfileString及WritePrivateProfileString函数直接读写系统配置ini文件(指定目录下的Ini文件)。

假设在当前目录下有一个文件名为Tets.ini的文件,用于保存用户名和密码,文件格式如下:

[Section1]

Item1= huzhifeng

Item2= 1234565

①写INI文件

voidCINI_File_TestDlg::OnButtonWrite()

{

// TODO: Add your control notification handler code here

CStringstrSection = "Section1";

CStringstrSectionKey = "Item1";

charstrBuff[256];

CStringstrValue = _T("");

CStringstrFilePath;

strFilePath=GetCurrentDirectory(256,strBuff); // 获取当前路径。

strFilePath.Format("%s\\Test.ini",strBuff);

GetDlgItemText(IDC_EDIT_NAME,strValue);           // 获取文本框内容:即姓名。

// 写入ini文件中相应字段。

WritePrivateProfileString(strSection,strSectionKey,strValue,strFilePath);

strSectionKey= "Item2";

GetDlgItemText(IDC_EDIT_PASSWORD,strValue);      // 获取文本框内容:即密码。

WritePrivateProfileString(strSection,strSectionKey,strValue,strFilePath);

}

②读INI文件内容

void CINI_File_TestDlg::OnButtonRead()

{

// TODO: Add your control notification handler code here

CString strSection ="Section1";

CString strSectionKey = "Item1";

char strBuff[256];

CString strValue = _T("");

CString strFilePath;

strFilePath=GetCurrentDirectory(256, strBuff);    //获取当前路径

strFilePath.Format("%s\\Test.ini", strBuff);

//读取ini文件中相应字段的内容

GetPrivateProfileString( strSection, strSectionKey,

NULL, strBuff,

80, strFilePath);

strValue = strBuff;

SetDlgItemText(IDC_EDIT_NAME, strValue);

strSectionKey = "Item2";

GetPrivateProfileString( strSection, strSectionKey,

NULL, strBuff,

80, strFilePath);

strValue=strBuff;

SetDlgItemText(IDC_EDIT_PASSWORD, strValue);

UpdateData(FALSE);

}

 

原文出处:(半未匀)曾文献老师

http://hi.baidu.com/__%B6%C0%B9%C2%B2%D0%D4%C6__/blog/item/79957c127edbd9c9c3fd78d0.html

BOOLIsFileExist(const char *szFileName) //判断文件是否存在

{

CFileStatus stat;

if(CFile::GetStatus(szFileName,stat))

return TRUE;

else

return FALSE;

}

 

// 读字符串

intReadINIString(CString INIFileName,CString INISection,CString Key,CString&Value) {

if(INIFileName=="" ||INISection=="" || Key=="") // 参数不对

{

Value.Format("%s",_T(""));

return -1;

}

if(!IsFileExist((LPTSTR)(LPCTSTR)INIFileName))   //ini文件不存在

{

Value.Format("%s",_T(""));

return -2;

}

::GetPrivateProfileString(INISection,Key,"",Value.GetBuffer(MAX_PATH),

MAX_PATH,INIFileName);

return 0;

}

 

//读整形变量

intReadINIUInt(CString INIFileName,CString INISection,CString Key,UINT &Value)

{

if(INIFileName=="" ||INISection=="" || Key=="")//参数不对

{

Value=0;

return -1;

}

if(!IsFileExist((LPTSTR)(LPCTSTR)INIFileName))//ini文件不存在

{

Value=0;

return -2;

}

Value=::GetPrivateProfileInt(INISection,Key,0,INIFileName);

return 0;

}

 

//获得应用程序的所在路径

intGetAppPath(CString &AppPath)

{

try

{

CString MoudleFile;

//得到文件绝对路径

GetModuleFileName(NULL,MoudleFile.GetBufferSetLength(MAX_PATH+1),MAX_PATH);

int pos=MoudleFile.ReverseFind(_T(‘\\‘));

AppPath=MoudleFile.Left(pos+1);

}catch(...){

return -1;

}

return 0;

}

 

//按钮事件调用相关函数

voidCReadWriteINIfieDlg::OnButton1()

{

// TODO: Add your control notification handler code here

CString FilePath;

//CString strServerToIEClientPort;

UINT iServerToIEClientPort;

GetAppPath(FilePath);

m_IniFileName.Format("%scc.ini",FilePath);

//ReadINIString(m_IniFileName,"ServerHost","Port",strServerToIEClientPort);

ReadINIUInt(m_IniFileName,"ServerHost","Port",iServerToIEClientPort);

ReadINIString(m_IniFileName,"ServerHost","DataFileName",strServerToIEClientPort);

}

 

//判断文件是否存在

BOOLIsFileExist(const char *szFileName)

{

CFileStatus stat;

if(CFile::GetStatus(szFileName,stat))

return TRUE;

else

return FALSE;

}

 

intCSetDbData::GetIniData( CString INIFileName, CString INISection,

CString Key, CString &Value)

{

if(INIFileName=="" ||INISection=="" || Key=="")//参数不对

{

Value.Format("%s",_T(""));

return -1;

}

if(!IsFileExist((LPTSTR)(LPCTSTR)INIFileName))//ini文件不存在

{

Value.Format("%s",_T(""));

return -2;

}

::GetPrivateProfileString(INISection,Key,"",

Value.GetBuffer(MAX_PATH),MAX_PATH,INIFileName);

return 0;

}

 

intCSetDbData::SetIniData(CString INIFileName,CString INISection,

CString Key,CString Value)

{

if(INIFileName=="" ||INISection=="" || Key=="")//参数不对

{

Value.Format("%s",_T(""));

return -1;

}

if(!IsFileExist((LPTSTR)(LPCTSTR)INIFileName))//ini文件不存在

{

Value.Format("%s",_T(""));

return -2;

}

::WritePrivateProfileString(INISection,Key,Value,INIFileName);

return 0;

}

 

//删除键

intCSetDbData::DelIniData(CString INIFileName,CString INISection)

{

if(INIFileName=="" ||INISection=="")//参数不对

{

return -1;

}

if(!IsFileExist((LPTSTR)(LPCTSTR)INIFileName))//ini文件不存在

{

return -2;

}

::WritePrivateProfileString(INISection,NULL,NULL,INIFileName);

return 0;

}

 

 

window平台下读写ini文件的一个小小的实例

http://hi.baidu.com/zerowwj/blog/item/5b088ea790fc429ad043586f.html

/* ini文件的读写 */

#include<iostream>

#include<windows.h>

#include<atlstr.h>

usingnamespace std;

voidmain()

{

CString strName;

CString strTemp;

int nAge;

strName = "zhangsan";

nAge = 12;

 

/*

* 此函数功能是向文件stud.ini文件里写入一段配置项记录:

* 其中配置段项名称为 "StudentInfo";配置项一个名称为Name;

* 其值为CString类型变量strName所指的内容

*/

::WritePrivateProfileString("StudentInfo","Name",strName,"d:\\stud.ini");

/*

* 此函数功能是向文件stud.ini文件里写入一段配置项记录:

* 其中配置段项名称为 "StudentInfo";配置项一个名称为Age;

* 其值为int类型变量nAge所指的内容,只是之前需要转换成CString类型

* 最后要指定写文件的路径和名称

*/

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

::WritePrivateProfileString("StudentInfo","Age",strTemp,"d:\\stud.ini");

/*

* 以下为读出,读出CString类型和int类型的方法不一样。函数的具体的功能可以查看MSDN

*/

CString strStudName;

int nStuAge;

::GetPrivateProfileString("StudentInfo","Name","defualt",

strStudName.GetBuffer(MAX_PATH),

MAX_PATH,"d:\\stud.ini");

nStuAge =::GetPrivateProfileInt("StudentInfo","Age",10,"d:\\stud.ini");

cout<<"strStudName = "<<strStudName <<endl;

cout<<"nStuAge = "<< nStuAge<<endl;

}

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!