| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1312 人关注过本帖
标题:大神们,求助,怎么读取ini文件!!!
只看楼主 加入收藏
ccz9305
Rank: 1
等 级:新手上路
帖 子:11
专家分:7
注 册:2013-8-27
结帖率:33.33%
收藏
已结贴  问题点数:20 回复次数:12 
大神们,求助,怎么读取ini文件!!!
我是初学者,怎么用c语言读取指定的配置文件,个位大神,求助!!!
搜索更多相关主题的帖子: 配置文件 c语言 
2013-09-26 15:58
303770957
Rank: 11Rank: 11Rank: 11Rank: 11
等 级:小飞侠
威 望:6
帖 子:838
专家分:2125
注 册:2005-9-10
收藏
得分:3 
虽然微软早已经建议在WINDOWS中用注册表代替INI文件,但是在实际应用中,INI文件仍然有用武之地,尤其现在绿色软件的流行,越来越多的程序将自己的一些配置信息保存到了INI文件中。
INI文件是文本文件,由若干节(section)组成,在每个带括号的标题下面,是若干个关键词(key)及其对应的值(Value)
[Section]
Key=Value
VC中提供了API函数进行INI文件的读写操作,但是微软推出的C#编程语言中却没有相应的方法,下面我介绍一个读写INI文件的C#类并利用该类保存窗体的坐标,当程序再次运行的时候,窗体将显示在上次退出时的位置。
INIFILE类:
using System;
using
using System.Runtime.InteropServices;
//因为我们需要调用API函数,所以必须创建System.Runtime.InteropServices
命名空间以提供可用于访问 .NET 中的 COM 对象和本机 API 的类的集合。
using System.Text;
namespace Ini
{
     public class IniFile
     {
         public string path;    //INI文件名

         [DllImport("kernel32")]

         private static extern long WritePrivateProfileString(string section,string key,string val,string filePath);

         [DllImport("kernel32")]

         private static extern int GetPrivateProfileString(string section,string key,string def,StringBuilder retVal,int size,string filePath);

         //声明读写INI文件的API函数  
         public IniFile(string INIPath)
         {

              path = INIPath;

         }

         //类的构造函数,传递INI文件名

         public void IniWriteValue(string Section,string Key,string Value)

         {

              WritePrivateProfileString(Section,Key,Value,this.path);

         }

         //写INI文件
        public string IniReadValue(string Section,string Key)

         {

              StringBuilder temp = new StringBuilder(255);

              int i = GetPrivateProfileString(Section,Key,"",temp,255,this.path);

              return temp.ToString();

         }

         //读取INI文件指定

     }

}

 

调用INIFILE类:
新建一个标准的C# WINDOWS应用程序项目,在窗体中分别增加命名为sect、key、val的三个文本框。

增加如下代码:

using Ini;    //创建命名空间

//当窗体关闭时保存窗体坐标

private void Form1_Closing(object sender, e)
{

              IniFile ini = new IniFile("C:\\test.ini");

              ini.IniWriteValue("LOC" ,"x" ,this.Location.X.ToString()   );

              ini.IniWriteValue("LOC " ,"y" ,this.Location.Y.ToString()   );

              //ToString方法将数字转换为字符串

 }

//当窗体启动时,读取INI文件的值并赋值给窗体
 private void Form1_Load(object sender, System.EventArgs e)
{

              IniFile ini = new IniFile("C:\\test.ini");

              Point    p=new Point() ;

              if ((ini.IniReadValue ("LOC" ,"x" )!="" ) && (ini.IniReadValue ("LOC" ,"y" )!=""))

              //判断返回值,避免第一次运行时为空出错

              {

                   p.X=int.Parse (ini.IniReadValue ("LOC" ,"x" ));

                   p.Y =int.Parse (ini.IniReadValue ("LOC" ,"y" ));

                   // int.Parse将字符串转换为int

                   this.Location =p;

              }

}

另一个c++的类:
第一个文件是INIFILE.h
#include <algorithm>
#include <vector>
class KEY  
{
public:
    KEY(char* Source);
    char Name[255];
    char Value[255];
    KEY();
    virtual ~KEY();

};
class SECTION  
{
public:
    int count();
    char Name[255];
    char Value[255];
    SECTION();
    SECTION(char* Source);
    virtual ~SECTION();
    std::vector<KEY> Key;
};
class INIFILE  
{
public:
    void save();
    KEY* GetKey(char *SecName, char* SecValue, char *KeyName);
    SECTION* GetSec(char *SecName,char *SecValue);
    void SetKey(char* SecName,char* SecValue,char* KeyName,char* KeyValue);
    void SetSec(char* SecName,char* SecValue);
    void Init(char* Source);
    void Init();
    int count();
    KEY* GetKey(char* SecName,char* KeyName);
    SECTION* GetSec(char* SecName);
   
    INIFILE();
    INIFILE(char* Source);
    virtual ~INIFILE();
    std::vector<SECTION> Section;  
protected:
    char IniFile[255];
};

第二个文件是INIFILE.cpp
#include "INIFILE.h"
#include <string>
#include <fstream.h>
#include <strstrea.h>


//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

INIFILE::INIFILE()
{
    memset(IniFile,0,255);
}
INIFILE::INIFILE(char* Source)
{
    memset(IniFile,0,255);
    strncpy(IniFile,Source,254);
}


INIFILE::~INIFILE()
{

}

//////////////////////////////////////////////////////////////////////
// SECTION Class
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
SECTION::SECTION()
{
    memset(Name,0,255);
    memset(Value,0,255);
}
SECTION::SECTION(char* Source)
{
    memset(Name,0,255);
    memset(Value,0,255);
    char Tmp[255]={0};
    int i=0;
    while(isspace(Source[i]))i++;
    while(Source[i]=='[')i++;
   
    char* pr=strstr(&Source[i],"]");
    if(pr)
        strncpy(Tmp,&Source[i],pr-&Source[i]);
    else
        strcpy(Tmp,&Source[i]);
   
    char* ipos=strstr(Tmp,"=");
    if(ipos){
        int iName=ipos-Tmp;        
        strncpy(Name,Tmp,iName);
        strcpy(Value,ipos+1);
    }
    else
    {
        strcpy(Name,Tmp);
    }
}

SECTION::~SECTION()
{

}

//////////////////////////////////////////////////////////////////////
// KEY Class
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

KEY::KEY()
{

}

KEY::~KEY()
{

}

SECTION* INIFILE::GetSec(char *SecName)
{
    for(int i=0;i<Section.size();i++)
        if(strstr(Section[i].Name,SecName))
            return &Section[i];
    return 0;
}
KEY* INIFILE::GetKey(char *SecName, char *KeyName)
{
    SECTION* Sec=GetSec(SecName);
    if(Sec!=0)
    {
        for(int i=0;i<Sec->count();i++)
        {
            if(strstr(Sec->Key[i].Name,KeyName))
                return &Sec->Key[i];
        }
    }
    return 0;
}
void INIFILE::Init()
{
    ifstream F(IniFile);
    if(F){
        char buf[255]={0};
        while(F.getline(buf,255)){
            int i=0;
            while(isspace(buf[i]))i++;
            if(&buf[i])
            {
                switch(buf[i])
                {
                case '[':
                    {
                    SECTION NewSec(&buf[i]);
                    Section.push_back(NewSec);
                    }
                    break;
                default:
                    {
                    KEY NewKey(&buf[i]);
                    Section.back().Key.push_back(NewKey);
                    }
                    break;
                }
            }
            memset(buf,0,255);
        }
    }
}

int INIFILE::count(){
    return Section.size();
}

void INIFILE::Init(char *Source)
{
    memset(IniFile,0,255);
    strncpy(IniFile,Source,254);
}

KEY::KEY(char *Source)
{
    memset(Name,0,255);
    memset(Value,0,255);
    char Tmp[255]={0};
    int i=0;
    while(isspace(Source[i]))i++;
    while(Source[i]=='[')i++;
   
    char* pr=strstr(&Source[i],"]");
    if(pr)
        strncpy(Tmp,&Source[i],pr-&Source[i]);
    else
        strcpy(Tmp,&Source[i]);
   
    char* ipos=strstr(Tmp,"=");
    if(ipos){
        int iName=ipos-Tmp;        
        strncpy(Name,Tmp,iName);
        strcpy(Value,ipos+1);
    }
    else
    {
        strcpy(Name,Tmp);
    }
}

int SECTION::count()
{
    return Key.size();
}

void INIFILE::SetSec(char *SecName, char *SecValue)
{
    int i=0;
    while(isspace(SecName[i]))i++;
    for(int j=0;j<Section[i].count();j++)
        if((strstr(Section[i].Name,&SecName[i]))&&
            (strstr(Section[i].Value,&SecValue[i])))
                return;

    {
        SECTION NewSec;
        strcpy(NewSec.Name,SecName);
        strcpy(NewSec.Value,SecValue);
        Section.push_back(NewSec);
    }
}

void INIFILE::SetKey(char *SecName, char *SecValue, char *KeyName, char *KeyValue)
{
    SetSec(SecName,SecValue);
    SECTION* Sec=GetSec(SecName,SecValue);
    if(Sec==0)return;
    for(int i=0;i<Sec->count();i++)
    {
        if(strstr(Sec->Key[i].Name,KeyName))
        {
            strcpy(Sec->Key[i].Value,KeyValue);
            return;
        }
    }
    {
        KEY NewKey;
        strcpy(NewKey.Name,KeyName);
        strcpy(NewKey.Value,KeyValue);
        Sec->Key.push_back(NewKey);
    }
}

SECTION* INIFILE::GetSec(char *SecName, char *SecValue)
{
    for(int i=0;i<Section.size();i++)
        if((strstr(Section[i].Name,SecName))&&(strstr(Section[i].Value,SecValue)))
            return &Section[i];
    return 0;
}

KEY* INIFILE::GetKey(char *SecName, char *SecValue, char *KeyName)
{
    SECTION* Sec=GetSec(SecName,SecValue);
    if(Sec!=0)
    {
        for(int i=0;i<Sec->count();i++)
        {
            if(strstr(Sec->Key[i].Name,KeyName))
                return &Sec->Key[i];
        }
    }
    return 0;
}

void INIFILE::save()
{
    int i=0,j=0;
    ofstream OutPut("E:\\3.ini");
    for(i=0;i<this->count();i++)
    {
        OutPut << "[" << Section[i].Name;
        if(strlen(Section[i].Value)>0)
            OutPut << "=" << Section[i].Value;
        OutPut  << "]" << endl;
        for(j=0;j<Section[i].count();j++)
        {
            OutPut << Section[i].Key[j].Name << "=" << Section[i].Key[j].Value << endl;
        }
    }
}

然后是main.cpp,相当于使用说明
//main.cpp
    INIFILE X("E:\\1.ini");
    X.Init();
    KEY* Key=X.GetKey("USER","gzh","Note1");
    if(Key!=0){
        cout << Key->Name << endl;
        cout << Key->Value << endl;
    }
    X.SetKey("USER","gzh","Note1","this is a test");
    cout << endl;
    Key=X.GetKey("USER","gzh","Note1");
    if(Key!=0){
        cout << Key->Name << endl;
        cout << Key->Value << endl;
    }
    X.save();
    X.Init("E:\\3.ini");
    Key=X.GetKey("USER","gzh","Note1");
    if(Key!=0){
        cout << Key->Name << endl;
        cout << Key->Value << endl;
 }

希望你能看明白!
收到的鲜花
  • ccz93052013-09-27 10:20 送鲜花  3朵   附言:我很赞同

♂ 死后定当长眠,生前何须久睡。♀
2013-09-26 16:22
pauljames
Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19
等 级:千里冰封
威 望:9
帖 子:1555
专家分:10000
注 册:2011-5-8
收藏
得分:3 
当作txt来读
收到的鲜花
  • ccz93052013-09-27 10:21 送鲜花  3朵   附言:给了我一个思路
  • ccz93052013-09-27 10:21 送鲜花  3朵   附言:给了我一个思路

经常不在线不能及时回复短消息,如有c/单片机/运动控制/数据采集等方面的项目难题可加qq1921826084。
2013-09-26 18:26
peach5460
Rank: 15Rank: 15Rank: 15Rank: 15Rank: 15
来 自:武汉
等 级:贵宾
威 望:30
帖 子:2780
专家分:6060
注 册:2008-1-28
收藏
得分:3 
微软底层不是有4个还是6个解析ini的接口么?

我总觉得授人以鱼不如授人以渔...
可是总有些SB叫嚣着:要么给代码给答案,要么滚蛋...
虽然我知道不要跟SB一般见识,但是我真的没修炼到宠辱不惊...
2013-09-27 08:35
ccz9305
Rank: 1
等 级:新手上路
帖 子:11
专家分:7
注 册:2013-8-27
收藏
得分:0 
回复 2楼 303770957
谢谢前辈的代码,不懂得地方我会查的!
2013-09-27 10:15
ccz9305
Rank: 1
等 级:新手上路
帖 子:11
专家分:7
注 册:2013-8-27
收藏
得分:0 
回复 3楼 pauljames
谢谢,
2013-09-27 10:16
ccz9305
Rank: 1
等 级:新手上路
帖 子:11
专家分:7
注 册:2013-8-27
收藏
得分:0 
回复 3楼 pauljames
谢谢这位前辈的提醒,我试试
2013-09-27 10:17
ccz9305
Rank: 1
等 级:新手上路
帖 子:11
专家分:7
注 册:2013-8-27
收藏
得分:0 
回复 4楼 peach5460
恩,好的,我找找看
2013-09-27 10:19
Alar30
Rank: 10Rank: 10Rank: 10
等 级:贵宾
威 望:10
帖 子:988
专家分:1627
注 册:2009-9-8
收藏
得分:3 
确实现在不少ini是以txt形式读取的
2013-09-27 11:29
TonyDeng
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:贵宾
威 望:304
帖 子:25859
专家分:48889
注 册:2011-6-22
收藏
得分:3 
.ini本來就沒規定是什麽格式的,純粹一個文件後綴而已,不過是Initialization File的意思。很多種外部初始化數據和參數設置文件,都可以起.ini的名字,也完全可以用別的名字,那是程序自己使用的。Windows上的.ini只是它自己使用的格式,其實.net上也使用.ini,是用xml語法的,這些本來就是普通的文本文件,關鍵是你要解釋它怎麽用,知道每一項的意義,而不是怎麽讀。

[ 本帖最后由 TonyDeng 于 2013-9-27 11:39 编辑 ]

授人以渔,不授人以鱼。
2013-09-27 11:37
快速回复:大神们,求助,怎么读取ini文件!!!
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014187 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved