用 Windows API 创建和编辑 .ini 文件

本文介绍如何利用Windows API进行.ini文件的创建和编辑,包括操作Win.ini的相关函数,以及参考MSDN在线文档和VC的具体实践示例。
摘要由CSDN通过智能技术生成

1. 与 .ini 文件相关的 API 有两类:

1)操作系统配置文件 Win.ini 的函数

GetProfileSection
GetProfileString
GetProfileInt
WriteProfileSection
WriteProfileString
2)操作用户自定义配置文件 PrivateProfile.ini 的函数

GetPrivateProfileSectionNames
GetPrivateProfileSection
GetPrivateProfileString
GetPrivateProfileInt
GetPrivateProfileStruct
WritePrivateProfileSection
WritePrivateProfileString
WritePrivateProfileStruct
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 = w
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值