用 Windows API 建立和編輯 .ini 檔案

來源:互聯網
上載者:User

1. 與 .ini 檔案相關的 API 有兩類:

1)作業系統設定檔 Win.ini 的函數

GetProfileSectionGetProfileStringGetProfileIntWriteProfileSectionWriteProfileString

2)操作使用者自訂設定檔 PrivateProfile.ini 的函數

GetPrivateProfileSectionNamesGetPrivateProfileSectionGetPrivateProfileStringGetPrivateProfileIntGetPrivateProfileStructWritePrivateProfileSectionWritePrivateProfileStringWritePrivateProfileStruct

2. 操作使用者自訂設定檔相關 API 的範例程式碼

#include <Windows.h>#include <tchar.h>#include <strsafe.h>#pragma comment(lib, "strsafe.lib") #define INI_FILE_NAME _T("ini_test.ini") TCHAR gIniFileFullPath[MAX_PATH] = {_T('\0')}; int main(){    DWORD dwRet = 0;    BOOL  bRet  = FALSE;     // 擷取 ini 檔案全路徑    dwRet = ::GetModuleFileName(NULL, gIniFileFullPath, MAX_PATH);    if (0UL == dwRet)    {        _ftprintf(stderr, _T("Error: Error occurs in calling GetModuleFileName, ")                          _T("error code is %lu.\n"),                           ::GetLastError());        return -1;    }    if (MAX_PATH == dwRet && ERROR_INSUFFICIENT_BUFFER == ::GetLastError())    {        _ftprintf(stderr, _T("Error: The buffer is too small to hold the module name.\n"));        return -1;    }     _tprintf(_T("The full path for the current module is: \n\t%s\n"), gIniFileFullPath);     DWORD dwLoopIdx = dwRet - 1;     while (gIniFileFullPath[dwLoopIdx] != _T('\\'))    {        --dwLoopIdx;    }    ::StringCchCopy(gIniFileFullPath + (dwLoopIdx + 1), MAX_PATH - (dwLoopIdx + 1), INI_FILE_NAME);    _tprintf(_T("The full path for %s is: \n\t%s\n"), INI_FILE_NAME, gIniFileFullPath);        // ---------------------------------------------- WritePrivateProfileSection    // 注: 如果 gIniFileFullPath 表示的 .ini 檔案不存在, 會先建立一個.    TCHAR szInsertedKeyValuePair[1024] = {_T('\0')}; #if defined(_UNICODE) || defined(UNICODE)    wchar_t* dest  = NULL;    wchar_t* src   = NULL;    size_t   count = 0;     dest  = szInsertedKeyValuePair;    src   = L"Key11=defaultValue11";    count = wcslen(L"Key11=defaultValue11");    wmemcpy(dest, src, count);     dest += count;    src   = L"\0";    count = 1;    wmemcpy(dest, src, count);     dest += count;    src   = L"Key12=defaultValue12";    count = wcslen(L"Key12=defaultValue12");    wmemcpy(dest, src, count);     dest += count;    src   = L"\0";    count = 1;    wmemcpy(dest, src, count);     dest += count;    src   = L"Key13=defaultValue13";    count = wcslen(L"Key13=defaultValue13");    wmemcpy(dest, src, count);     dest += count;    src   = L"\0";    count = 1;    wmemcpy(dest, src, count);#else    char*  dest  = NULL;    char*  src   = NULL;    size_t count = 0;     dest  = szInsertedKeyValuePair;    src   = "Key11=defaultValue11";    count = strlen("Key11=defaultValue11");    memcpy(static_cast<void*>(dest), static_cast<void*>(src), count);     dest += count;    src   = "\0";    count = 1;    memcpy(static_cast<void*>(dest), static_cast<void*>(src), count);     dest += count;    src   = "Key12=defaultValue12";    count = strlen("Key12=defaultValue12");    memcpy(static_cast<void*>(dest), static_cast<void*>(src), count);     dest += count;    src   = "\0";    count = 1;    memcpy(static_cast<void*>(dest), static_cast<void*>(src), count);     dest += count;    src   = "Key13=defaultValue13";    count = strlen("Key13=defaultValue13");    memcpy(static_cast<void*>(dest), static_cast<void*>(src), count);     dest += count;    src   = "\0";    count = 1;    memcpy(static_cast<void*>(dest), static_cast<void*>(src), count);#endif // defined(_UNICODE) || defined(UNICODE)     bRet = ::WritePrivateProfileSection(_T("Section1"), szInsertedKeyValuePair, gIniFileFullPath);    if (FALSE == bRet)    {        _ftprintf(stderr, _T("Error: Error occurs in calling WritePrivateProfileSection, ")                          _T("error code is %lu.\n"),                           ::GetLastError());        return -1;    }    // ---------------------------------------------- WritePrivateProfileSection     // ----------------------------------------------- WritePrivateProfileString    TCHAR szStr4Int[10] = {_T('\0')};    _itot(-77, szStr4Int, 10);    bRet = ::WritePrivateProfileString(_T("Section1"), _T("Key12"), szStr4Int, gIniFileFullPath);    if (FALSE == bRet)    {        _ftprintf(stderr, _T("Error: Error occurs in calling WritePrivateProfileString, ")                          _T("error code is %lu.\n"),                           ::GetLastError());        return -1;    }     bRet = ::WritePrivateProfileString(_T("Section1"), _T("Key13"), _T("Value13"), gIniFileFullPath);    if (FALSE == bRet)    {        _ftprintf(stderr, _T("Error: Error occurs in calling WritePrivateProfileString, ")                          _T("error code is %lu.\n"),                           ::GetLastError());        return -1;    }    // ----------------------------------------------- WritePrivateProfileString     // ------------------------------------------- GetPrivateProfileSectionNames    TCHAR szReturnBuffer[1024] = {_T('\0')};    dwRet = ::GetPrivateProfileSectionNames(szReturnBuffer, 1024, gIniFileFullPath);    if (1024 - 2 == dwRet)    {        _ftprintf(stderr, _T("Error: szReturnBuffer is not large enough to ")                          _T("contain all the section names associated with ")                          _T("the specified initialization file.\n"));        return -1;    }    // ------------------------------------------- GetPrivateProfileSectionNames     // ------------------------------------------------ GetPrivateProfileSection    // 在 Section1 末尾追加 Key14=defaultValue14    dwRet = ::GetPrivateProfileSection(_T("Section1"), szReturnBuffer, 1024, gIniFileFullPath);    if (1024 - 2 == dwRet)    {        _ftprintf(stderr, _T("Error: szReturnBuffer is not large enough to ")                          _T("contain all the key name and value pairs ")                          _T("associated with Section1.\n"));        return -1;    } #if defined(_UNICODE) || defined(UNICODE)    dest  = szReturnBuffer + dwRet;    src   = L"Key14=DefaultValue14";    count = wcslen(L"Key14=DefaultValue14");    wmemcpy(dest, src, count);     dest += count;    src   = L"\0";    count = 1;    wmemcpy(dest, src, count);#else    dest  = szReturnBuffer + dwRet;    src   = "Key14=DefaultValue14";    count = strlen("Key14=DefaultValue14");    memcpy(static_cast<void*>(dest), static_cast<void*>(src), count);     dest += count;    src   = "\0";    count = 1;    memcpy(static_cast<void*>(dest), static_cast<void*>(src), count);#endif // defined(_UNICODE) || defined(UNICODE)     bRet = ::WritePrivateProfileSection(_T("Section1"), szReturnBuffer, gIniFileFullPath);    if (FALSE == bRet)    {        _ftprintf(stderr, _T("Error: Error occurs in calling WritePrivateProfileSection, ")                          _T("error code is %lu.\n"),                           ::GetLastError());        return -1;    }    // ------------------------------------------------ GetPrivateProfileSection     // ---------------------------------------------- WritePrivateProfileSection    // 在 .ini 檔案末尾追加 Section2     ZeroMemory(static_cast<void*>(szInsertedKeyValuePair), sizeof(szInsertedKeyValuePair)); #if defined(_UNICODE) || defined(UNICODE)    dest  = szInsertedKeyValuePair;    src   = L"Key21=defaultValue21";    count = wcslen(L"Key21=defaultValue21");    wmemcpy(dest, src, count);     dest += count;    src   = L"\0";    count = 1;    wmemcpy(dest, src, count);     dest += count;    src   = L"Key22=defaultValue22";    count = wcslen(L"Key22=defaultValue22");    wmemcpy(dest, src, count);     dest += count;    src   = L"\0";    count = 1;    wmemcpy(dest, src, count);#else    dest  = szInsertedKeyValuePair;    src   = "Key21=defaultValue21";    count = strlen("Key21=defaultValue21");    memcpy(static_cast<void*>(dest), static_cast<void*>(src), count);     dest += count;    src   = "\0";    count = 1;    memcpy(static_cast<void*>(dest), static_cast<void*>(src), count);     dest += count;    src   = "Key22=defaultValue22";    count = strlen("Key22=defaultValue22");    memcpy(static_cast<void*>(dest), static_cast<void*>(src), count);     dest += count;    src   = "\0";    count = 1;    memcpy(static_cast<void*>(dest), static_cast<void*>(src), count);#endif // defined(_UNICODE) || defined(UNICODE)     bRet = ::WritePrivateProfileSection(_T("Section2"), szInsertedKeyValuePair, gIniFileFullPath);    if (FALSE == bRet)    {        _ftprintf(stderr, _T("Error: Error occurs in calling WritePrivateProfileSection, ")                          _T("error code is %lu.\n"),                           ::GetLastError());        return -1;    }    // ---------------------------------------------- WritePrivateProfileSection     // ---------------------------------------------------- GetPrivateProfileInt    // 注: MSDN 中, 該函數原型的傳回值資料類型為 UINT, 但, 並非是說它只能返回    //     無符號整型值. 通過該函數, .ini 檔案中的負數是可以正確取得的.    int nIntValue4Key12 = ::GetPrivateProfileInt(_T("Section1"), _T("Key12"), -1, gIniFileFullPath);    _tprintf(_T("\nnIntValue4Key12 = %i\n"), nIntValue4Key12);    // ---------------------------------------------------- GetPrivateProfileInt     // ------------------------------------------------- GetPrivateProfileString    // Read value for Key11    dwRet = ::GetPrivateProfileString(_T("Section1"),                                       _T("Key11"),                                       _T("Key11 key cannot be found in the initialization file."),                                       szReturnBuffer,                                       MAX_PATH,                                       gIniFileFullPath);    if (MAX_PATH - 1 == dwRet)    {         _ftprintf(stderr, _T("Error: Neither lpAppName nor lpKeyName is NULL ")                          _T("and the supplied destination buffer is too small ")                          _T("to hold the requested string.\n"));        return -1;    }    if (MAX_PATH - 2 == dwRet)    {        _ftprintf(stderr, _T("Error: Either lpAppName or lpKeyName is NULL and ")                          _T("the supplied destination buffer is too small to ")                          _T("hold all the strings.\n"));        return -1;    }    _tprintf(_T("\nValue for Key11 is %s.\n"), szReturnBuffer);        // Read value for Key12    dwRet = ::GetPrivateProfileString(_T("Section1"),                                       _T("Key12"),                                       _T("Key12 key cannot be found in the initialization file."),                                       szReturnBuffer,                                       MAX_PATH,                                       gIniFileFullPath);    if (MAX_PATH - 1 == dwRet)    {         _ftprintf(stderr, _T("Error: Neither lpAppName nor lpKeyName is NULL ")                          _T("and the supplied destination buffer is too small ")                          _T("to hold the requested string.\n"));        return -1;    }    if (MAX_PATH - 2 == dwRet)    {        _ftprintf(stderr, _T("Error: Either lpAppName or lpKeyName is NULL and ")                          _T("the supplied destination buffer is too small to ")                          _T("hold all the strings.\n"));        return -1;    }    _tprintf(_T("Value for Key12 is %s.\n"), szReturnBuffer);        // Read value for Key13    dwRet = ::GetPrivateProfileString(_T("Section1"),                                       _T("Key13"),                                       _T("Key13 key cannot be found in the initialization file."),                                       szReturnBuffer,                                       MAX_PATH,                                       gIniFileFullPath);    if (MAX_PATH - 1 == dwRet)    {         _ftprintf(stderr, _T("Error: Neither lpAppName nor lpKeyName is NULL ")                          _T("and the supplied destination buffer is too small ")                          _T("to hold the requested string.\n"));        return -1;    }    if (MAX_PATH - 2 == dwRet)    {        _ftprintf(stderr, _T("Error: Either lpAppName or lpKeyName is NULL and ")                          _T("the supplied destination buffer is too small to ")                          _T("hold all the strings.\n"));        return -1;    }    _tprintf(_T("Value for Key13 is %s.\n\n"), szReturnBuffer);    // ------------------------------------------------- GetPrivateProfileString     return 0; }

    
參考:

1. MSDN 線上文檔

2. VC操作INI檔案

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.