C++讀寫ini配置文件


在Windows的VC下

讀ini文件

例如:在D:\test.ini文件中

[Font]
name=宋體
size= 12pt
color = RGB(255,0,0)

上面的=號兩邊可以加空格,也可以不加

GetPrivateProfileInt()和GetPrivateProfileString()

[section]
key=string
      .
      .

獲取integer
UINT GetPrivateProfileInt(
  LPCTSTR lpAppName,  // section name
  LPCTSTR lpKeyName,  // key name
  INT nDefault,       // return value if key name not found
  LPCTSTR lpFileName  // initialization file name
);

注意:lpAppName和lpKeyName不區分大小寫,當獲得integer <0,那么返回0。lpFileName  必須是絕對路徑,因相對路徑是以C:\windows\

DWORD GetPrivateProfileString(
  LPCTSTR lpAppName,        // section name
  LPCTSTR lpKeyName,        // key name
  LPCTSTR lpDefault,        // default string
  LPTSTR lpReturnedString,  // destination buffer
  DWORD nSize,              // size of destination buffer
  LPCTSTR lpFileName        // initialization file name
);

注意:lpAppName和lpKeyName不區分大小寫,若lpAppName為NULL,lpReturnedString緩沖區內裝載這個ini文件所有小節的列表,若為lpKeyName=NULL,就在lpReturnedString緩沖區內裝載指定小節所有項的列表。lpFileName  必須是絕對路徑,因相對路徑是以C:\windows\,
返回值:復制到lpReturnedString緩沖區的字符數量,其中不包括那些NULL中止字符。如lpReturnedString緩沖區不夠大,不能容下全部信息,就返回nSize-1(若lpAppName或lpKeyName為NULL,則返回nSize-2)

獲取某一字段的所有keys和values
DWORD GetPrivateProfileSection(
  LPCTSTR lpAppName,        // section name
  LPTSTR lpReturnedString,  // return buffer
  DWORD nSize,              // size of return buffer
  LPCTSTR lpFileName        // initialization file name
);

retrieves the names of all sections in an initialization file.
DWORD GetPrivateProfileSectionNames(
  LPTSTR lpszReturnBuffer,  // return buffer
  DWORD nSize,              // size of return buffer
  LPCTSTR lpFileName        // initialization file name
);
其實就等於,GetPrivateProfileString(NULL,NULL,lpszReturnedBuffer,nSize,lpFileName)
View Code

 例子:

    /* test.ini  "="號兩邊可以加空格,也可以不加
    [Font]
    name=宋體
    size= 12pt
    color = RGB(255,0,0)
    [Layout]
    [Body]
    */

    CString strCfgPath = _T("D:\\test.ini"); //注意:'\\'
    LPCTSTR lpszSection = _T("Font");
    int n = GetPrivateProfileInt(_T("FONT"), _T("size"), 9, strCfgPath);//n=12
    CString str;
    GetPrivateProfileString(lpszSection, _T("size"), _T("9pt"), str.GetBuffer(MAX_PATH), MAX_PATH, strCfgPath);
    str.ReleaseBuffer();//str="12pt"

    TCHAR buf[200] = { 0 };
    int nSize = sizeof(buf) / sizeof(buf[0]);
    GetPrivateProfileString(lpszSection, NULL, _T(""), buf, nSize, strCfgPath);
    //buf: "name\0size\0color\0\0"

    memset(buf, 0, sizeof(buf));
    GetPrivateProfileString(NULL, _T("size"), _T(""), buf, nSize, strCfgPath);//沒Section,_T("size")沒意義了,所以可以寫NULL
    //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);
    //buf: "Font\0Layout\0Body\0\0"

    memset(buf, 0, sizeof(buf));
    GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);
    //buf: "name=宋體\0size=12pt\0color=RGB(255,0,0)\0\0"   此時“=”兩邊不會有空格

    memset(buf, 0, sizeof(buf));
    GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等於GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);
    //buf: "Font\0Layout\0Body\0\0"

 寫ini文件

WritePrivateProfileString函數,沒有寫integer的,可以轉成string再寫入。

BOOL WritePrivateProfileString(
  LPCTSTR lpAppName,  // section name
  LPCTSTR lpKeyName,  // key name
  LPCTSTR lpString,   // string to add
  LPCTSTR lpFileName  // initialization file
);

The WritePrivateProfileSection function replaces the keys and values for the specified section in an initialization file. 

BOOL WritePrivateProfileSection(
  LPCTSTR lpAppName,  // section name
  LPCTSTR lpString,   // data
  LPCTSTR lpFileName  // file name
);

WritePrivateProfileString:

Remarks

If the lpFileName parameter does not contain a full path and file name for the file, WritePrivateProfileString searches the Windows directory for the file. If the file does not exist, this function creates the file in the Windows directory.

If lpFileName contains a full path and file name and the file does not exist, WritePrivateProfileString creates the file. The specified directory must already exist.

 

 

WritePrivateProfileSection:

Remarks

The data in the buffer pointed to by the lpString parameter consists of one or more null-terminated strings, followed by a final null character. Each string has the following form:

key=string

The WritePrivateProfileSection function is not case-sensitive; the string pointed to by the lpAppName parameter can be a combination of uppercase and lowercase letters.

If no section name matches the string pointed to by the lpAppName parameter, WritePrivateProfileSection creates the section at the end of the specified initialization file and initializes the new section with the specified key name and value pairs.

WritePrivateProfileSection deletes the existing keys and values for the named section and inserts the key names and values in the buffer pointed to by the lpString parameter. The function does not attempt to correlate old and new key names; if the new names appear in a different order from the old names, any comments associated with preexisting keys and values in the initialization file will probably be associated with incorrect keys and values.

This operation is atomic; no operations that read from or write to the specified initialization file are allowed while the information is being written.

 例子:

    WritePrivateProfileString(_T("Layout"), _T("left"), _T("100"), strCfgPath);
    WritePrivateProfileString(_T("Layout"), _T("top"), _T("80"), strCfgPath);
    //刪除某Section,包括[Layout]和其下所有Keys=Value
    WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);
    //刪除某Section,包括[Layout]下所有Keys=Value,但不刪除[Layout]
    WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);
//而:WritePrivateProfileSection(NULL, NULL, strCfgPath);什么也不做,因Section為NULL

 

自己封裝的函數:
獲取某一個Section的所有 key=value
map<CString, CString> GetKeysValues(LPCTSTR szSection, LPCTSTR szIniFilePath)
獲取ini文件的所有Section名
vector<CString> GetSectionsNames(LPCTSTR szIniFilePath)

#include <vector>
#include <map>
using std::vector;
using std::map;
//獲取ini文件的所有Section名
vector<CString> GetSectionsNames(LPCTSTR szIniFilePath)
{
    vector<CString> vRet;
    TCHAR buf[2048] = { 0 };
    long nSize = sizeof(buf) / sizeof(buf[0]);
    ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);
    TCHAR *p, *q;
    p = q = buf;
    while (*p)//即 '\0' != *p
    {
        while (*q)
        {
            ++q;
        }
        CString str(p, q - p);
        vRet.push_back(str);
        p = q + 1;
        q = q + 1;
    }
    return vRet;
}
//獲取某一個Section的所有 key=value
map<CString, CString> GetKeysValues(LPCTSTR szSection, LPCTSTR szIniFilePath)
{
    map<CString,CString> mapRet;
    TCHAR buf[2048] = { 0 };
    long nSize = sizeof(buf) / sizeof(buf[0]);
    GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);
    TCHAR* p = buf;
    TCHAR* q = buf;
    while (*p)
    {
        CString strKey, strValue;
        while(*q)
        {
            if (_T('=') == *q)
            {
                strKey = CString(p, q - p);
                p = q + 1;
            }
            ++q;
        }
        strValue = CString(p, q - p);
        mapRet.insert(std::make_pair(strKey, strValue));
        p = q + 1;
        q = q + 1;
    }
    return mapRet;
}
View Code

 

 相關知識鏈接

www.cnblogs.com/lishennan/p/5165136.html
blog.csdn.net/thanklife/article/details/52953475
blog.csdn.net/Dstar2/article/details/70242161/


 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM