zoukankan      html  css  js  c++  java
  • C++读写ini配置文件

    配置文件中经常用到ini文件,在VC中其函数分别为:

    写入.ini文件:bool WritePrivateProfileString(LPCTSTR lpAppName,LPCTSTR lpKeyName,LPCTSTR lpString,LPCTSTR lpFileName);

    读取.ini文件:DWORD GetPrivateProfileString(LPCTSTR lpAppName,LPCTSTR lpKeyName,LPCTSTR lpDefaut,LPSTR lpReturnedString,DWORD nSize,LPCTSTR lpFileName);

    读取整形值:UINT GetPrivateProfileInt(LPCTSTR lpAppName,LPCTSTR lpKeyName,INT nDefault,LPCTSTR lpFileName);

    其中个参数的意思:

    LPCTSTR lpAppName ------- INI文件中的一个字段名

    LPCTSTR lpKeyName -------- lpAppName 下的一个键名,也就是里面具体的变量名

    LPCTSTR lpString ---------是键值,也就是变量的值,必须为LPCTSTRCString类型

    LPCTSTR lpFileName --------完整的INI文件路径名

    LPCTSTR lpDefaut ----------如果没有其前两个参数值,则将此值赋给变量

    LPSTR lpReturnedString --------接收INI文件中的值的CString对象,即接收缓冲区

    DWORD nSize ------接收缓冲区的大小

    例子:

    CString StrName,Strtemp;

    int nAge;

    StrName = "jacky";

    nAge = 13;

    WritePrivateProfileString("Student","Name",StrName,"c:\\setting.ini");

    结果:(INI文件中显示如下:)

    [Student]

    Name=jacky

    读取:

    CString SName;

    GetPrivateProfileString("Student","Name","DefaultName",SName.GetBuffer(MAX_LENGTH),MAX_LENGTH,"c:\\setting.ini");

    结果:SName = "jacky";这里需要注意点就是用完GetBuffer函数后一定要释放(SName.ReleaseBuffer()函数),不然后面再用到SName的其他子函数就会失灵。

    读整数比较简单,如下

    int Result = GetPrivateProfileInt("Student","nAge",0,"c:\\setting.ini")返回值即为所读取的结果!

    GetPrivateProfileString最后一个参数是配置文件路径的参数,此路径只能是绝对路径,不能是相对路径,但现在我需要是我的exe文件能和我的配置文件在一起。因此我使用了GetCurrentDirectory函数。

    原代码如下:

    CString server_ip;

    CString des="";

    ::GetCurrentDirectory(MAX_PATHLENGTH,des.GetBuffer(MAX_PATHLENGTH));

    des.ReleaseBuffer();

    des+="\\config.ini";

    GetPrivateProfileString("PhoneDemo","Server_IP","",server_ip.GetBufferSetLength(15),15,des);

    server_ip.ReleaseBuffer();

    注意:在这里使用CString变量时,在使用完GetBuffer后,紧接着一定要使用ReleaseBuffer()函数,才可以进行其他的诸如字符串+操作

    char m_szCurrPath[255];   

    GetModuleFileName(::GetModuleHandle(NULL),m_szCurrPath,255); 

    (_tcsrchr(m_szCurrPath, _T('\\')))[1] = 0; //删除文件名,只获得路径

    CString IniPath;

    CString IPAddress;

    IniPath.Format("%sCTC.ini",m_szCurrPath);

    //读取ini文件

    GetPrivateProfileString("DataBase","IP","IP",IPAddress.GetBuffer(255),255,IniPath);

    源文档 <http://apps.hi.baidu.com/share/detail/3553518>

  • 相关阅读:
    error occurred during initialization of vm
    Service Discovery protocol(SDP)
    nRF51822EK_PRO
    Binder
    android samsung note3  device not found
    BLE pairing vs. bonding
    remote link Centos6.6 Horrible Slow
    depmod -a
    start and end call use itelephony and how to pick up a call
    WebService
  • 原文地址:https://www.cnblogs.com/hhdllhflower/p/2711660.html
Copyright © 2011-2022 走看看