MFC读写配置ini文件

https://blog.csdn.net/naibozhuan3744/article/details/78783446

https://blog.csdn.net/rayborn1105/article/details/8192142

https://blog.csdn.net/g5dsk/article/details/6860162

// ConsoleApplication1.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <windows.h>

//using namespace std;

int main()
{

    //std::string strName, strTemp;
    //int nAge;
    //strName = "张三";
    //nAge = 12;
    //::WritePrivateProfileString(TEXT("StudentInfo"), TEXT("Name"), TEXT("张三"), TEXT(".\student.ini"));

    // write
    WritePrivateProfileString(TEXT("LiMing"), TEXT("Sex"), TEXT("Man"), TEXT(".\student.ini"));// 路径realse
    WritePrivateProfileString(TEXT("LiMing"), TEXT("Age"), TEXT("20"), TEXT(".\student.ini"));
    WritePrivateProfileString(TEXT("Fangfang"), TEXT("Sex"), TEXT("Woman"), TEXT(".\student.ini"));
    WritePrivateProfileString(TEXT("Fangfang"), TEXT("Age"), TEXT("21"), TEXT(".\student.ini"));

    // read

    LPTSTR LiMingSex = new  TCHAR[6] ;
    int LiMingAge = 0;
    LPTSTR FangfangSex = new  TCHAR[6];;
    int FangfangAge = 0;
    GetPrivateProfileString(TEXT("LiMing"), TEXT("Sex"), TEXT(""), LiMingSex, 6 ,TEXT(".\student.ini"));
    LiMingAge = GetPrivateProfileInt(TEXT("LiMing"), TEXT("Age"), 0, TEXT(".\student.ini"));

    char LM[6] = {0};
    strncpy_s(LM, (char *)LiMingSex,3);

    system("pause");
    return 0;
}
[Section1]

Key11=value11

Key12=value12

[Section2]

Key21=value21

Key22=value22

...

[SectionN]

KeyN1=valueN1

KeyN2=valueN2

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

 

函数名

功能

GetProfileSection

读取win.ini中指定节lpAppName中所有键名及其值。lpReturnedString字符串形式如下:

Key1=Value1/0Key2=Value2/0…KeyN=ValueN/0/0

GetProfileString

读取win.ini中指定节lpAppName中键名为lpKeyName对应变量的字符串值。

GetProfileInt

读取win.ini中指定节lpAppName中键名为lpKeyName对应变量的整数值。

WriteProfileSection

写(替换)win.ini中指定节lpAppName中的键值。

lpString字符串形式同GetProfileSection中的lpReturnedString

WriteProfileString

写(替换)win.ini中指定节lpAppName中键名为lpKeyName对应变量的字符串值。

 (2)操作用户自定义配置文件(PrivateProfile.ini)的函数:

 

函数名

功能

GetPrivateProfileSectionNames

读取lpFileName指定的配置文件中所有的节名。lpszReturnBuffer字符串形式如下:

Section1/0Section2/0…SectionN/0/0

GetPrivateProfileSection

GetProfileSection。

GetPrivateProfileString

GetProfileString。

GetPrivateProfileInt     

GetProfileInt

GetPrivateProfileStruct

须同WritePrivateProfileStruct配套使用。

WritePrivateProfileSection

WriteProfileSection

WritePrivateProfileString

WriteProfileString

WritePrivateProfileStruct

不常用。

用MFC配置ini文件的核心函数有三个,分别为WritePrivateProfileString和GetPrivateProfileString和GetPrivateProfileInt。下面分别讲解这三个核心函数的功能和各个参数的意义。

WritePrivateProfileString函数

BOOL  WritePrivateProfileString(

       LPCTSTRlpAppName,

       LPCTSTRlpKeyName,

       LPCTSTRlpString,

       LPCTSTRlpFileName

       );

//其中各参数的意义:

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

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

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

LPCTSTR lpFileName;//是完整的INI文件名.
WritePrivateProfileString("StudentInfo1","身份证","44022520070001",".\ConfigFile\ConfigInit.ini");
[StudentInfo]

Name = 李四

Age = 18

身份证 = 44022520070309

[StudentInfo1]

Name = 李四

Age = 18

身份证 = 44022520070309

GetPrivateProfileString函数

DWORD  GetPrivateProfileString(

       LPCTSTRlpAppName,

       LPCTSTRlpKeyName,

       LPCTSTRlpDefault,

       LPTSTRlpReturnedString,

       DWORDnSize,

       LPCTSTRlpFileName

       );

//其中各参数的意义:

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

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

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

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

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

nSize;// : 目的缓存器的大小.

lpFileName;// : 是完整的INI文件名.

GetPrivateProfileInt函数

UINT  GetPrivateProfileInt(

       LPCTSTRlpAppName,

       LPCTSTRlpKeyName,

       INTnDefault,

       LPCTSTRlpFileName

       );//其中各参数的意义:

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

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

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

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

LPCTSTR lpFileName;//是完整的INI文件名.
调用

GetPrivateProfileInt("StudentInfo2","Age", 1,".\ConfigFile\ConfigInit.ini");
#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('')};
 
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.
"), 
                          ::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.
"));
        return -1;
    }
 
    _tprintf(_T("The full path for the current module is: 
	%s
"), 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: 
	%s
"), INI_FILE_NAME, gIniFileFullPath);
    
    // ---------------------------------------------- WritePrivateProfileSection
    // 注: 如果 gIniFileFullPath 表示的 .ini 文件不存在, 会先创建一个.
    TCHAR szInsertedKeyValuePair[1024] = {_T('')};
 
#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"";
    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"";
    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"";
    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   = "";
    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   = "";
    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   = "";
    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.
"), 
                          ::GetLastError());
        return -1;
    }
    // ---------------------------------------------- WritePrivateProfileSection
 
    // ----------------------------------------------- WritePrivateProfileString
    TCHAR szStr4Int[10] = {_T('')};
    _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.
"), 
                          ::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.
"), 
                          ::GetLastError());
        return -1;
    }
    // ----------------------------------------------- WritePrivateProfileString
 
    // ------------------------------------------- GetPrivateProfileSectionNames
    TCHAR szReturnBuffer[1024] = {_T('')};
    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.
"));
        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.
"));
        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"";
    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   = "";
    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.
"), 
                          ::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"";
    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"";
    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   = "";
    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   = "";
    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.
"), 
                          ::GetLastError());
        return -1;
    }
    // ---------------------------------------------- WritePrivateProfileSection
 
    // ---------------------------------------------------- GetPrivateProfileInt
    // 注: MSDN 中, 该函数原型的返回值数据类型为 UINT, 但, 并非是说它只能返回
    //     无符号整型值. 通过该函数, .ini 文件中的负数是可以正确取得的.
    int nIntValue4Key12 = ::GetPrivateProfileInt(_T("Section1"), _T("Key12"), -1, gIniFileFullPath);
    _tprintf(_T("
nIntValue4Key12 = %i
"), 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.
"));
        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.
"));
        return -1;
    }
    _tprintf(_T("
Value for Key11 is %s.
"), 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.
"));
        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.
"));
        return -1;
    }
    _tprintf(_T("Value for Key12 is %s.
"), 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.
"));
        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.
"));
        return -1;
    }
    _tprintf(_T("Value for Key13 is %s.

"), szReturnBuffer);
    // ------------------------------------------------- GetPrivateProfileString
 
    return 0; 
原文地址:https://www.cnblogs.com/xiangtingshen/p/10715582.html