在一些场合,需要对一些配置文件进行读取,去设置软件的参数,自己实现了一些接口函数,以供以后使用。

ConfigFile.c

 #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <direct.h>
#define MAX_LINE_LENGTH 256 int read_line(FILE *fp, char *bp)
{
char c = '\0';
int i = ;
bool isAssgin = ;
/* Read one line from the source file */
while ()
{
c = getc(fp);
if (c == '\n')
{
break;
} if (c == '\r')
{
continue;
} if (c == '=')
{
isAssgin = ;
} if (feof(fp))
{
/* return FALSE on unexpected EOF */
if (isAssgin == )
{
bp[i] = '\0';
return();
}
else
{
return();
}
}
bp[i++] = c;
}
bp[i] = '\0';
return();
}
/************************************************************************
* Function: Get_private_profile_int()
* Arguments: <char *> section - the name of the section to search for
* <char *> entry - the name of the entry to find the value of
* <int> def - the default value in the event of a failed read
* <char *> file_name - the name of the .ini file to read from
* Returns: the value located at entry
*************************************************************************/
int Get_private_profile_int(const char *section, const char *entry, int def, char *file_name)
{
FILE *fp = fopen(file_name, "r");
//Try to fix the issue that the MAX_PATH should be 256, not 80
char buff[MAX_LINE_LENGTH];
char *ep;
char t_section[MAX_LINE_LENGTH];
char value[];
int len = strlen(entry);
int i;
//To support negative number convert
bool b_IsNegative = false;
if (!fp)
{
return();
}
sprintf(t_section, "[%s]", section); /* Format the section name */
/* Move through file 1 line at a time until a section is matched or EOF */
do
{
if (!read_line(fp, buff))
{
fclose(fp);
return(def);
}
}while (strcmp(buff, t_section));
/* Now that the section has been found, find the entry.
* Stop searching upon leaving the section's area. */
do
{
if (!read_line(fp, buff) || buff[] == '[') //130516 Willy modify '\0' to '[' for parser ini bug.
{
fclose(fp);
return(def);
}
}while (strncmp(buff, entry, len)); ep = strrchr(buff, '='); /* Parse out the equal sign */
ep++;
if (!strlen(ep)) /* No setting? */
{
return(def);
}
/* Copy only numbers fail on characters */
//To support negative number convert
if (ep[] == '-')
{
b_IsNegative = true;
for (i = ; isdigit(ep[i]); i++)
{
value[i - ] = ep[i];
}
value[--i] = '\0';
}
else
{
for (i = ; isdigit(ep[i]); i++)
{
value[i] = ep[i];
}
value[i] = '\0';
}
fclose(fp); /* Clean up and return the value */
//To support negative number convert
if (b_IsNegative)
{
return ( - atoi(value));
}
else
{
return(atoi(value));
}
} unsigned long long Get_private_profile_longlong(const char *section, const char *entry, unsigned long long def, char *file_name)
{
FILE *fp = fopen(file_name, "r");
char buff[MAX_LINE_LENGTH];
char *ep;
char t_section[MAX_LINE_LENGTH];
char value[];
int len = strlen(entry);
int i;
if (!fp)
{
return();
}
sprintf(t_section, "[%s]", section); /* Format the section name */
/* Move through file 1 line at a time until a section is matched or EOF */
do
{
if (!read_line(fp, buff))
{
fclose(fp);
return(def);
}
}while (strcmp(buff, t_section));
/* Now that the section has been found, find the entry.
* Stop searching upon leaving the section's area. */
do
{
if (!read_line(fp, buff) || buff[] == '[') //130516 Willy modify '\0' to '[' for parser ini bug.
{
fclose(fp);
return(def);
}
}while (strncmp(buff, entry, len)); ep = strrchr(buff, '='); /* Parse out the equal sign */
ep++;
if (!strlen(ep)) /* No setting? */
{
return(def);
}
/* Copy only numbers fail on characters */
for (i = ; isdigit(ep[i]); i++)
{
value[i] = ep[i];
}
value[i] = '\0';
fclose(fp); /* Clean up and return the value */
return(_atoi64(value));
} /**************************************************************************
* Function: Get_private_profile_string()
* Arguments: <char *> section - the name of the section to search for
* <char *> entry - the name of the entry to find the value of
* <char *> def - default string in the event of a failed read
* <char *> buffer - a pointer to the buffer to copy into
* <int> buffer_len - the max number of characters to copy
* <char *> file_name - the name of the .ini file to read from
* Returns: the number of characters copied into the supplied buffer
***************************************************************************/
int Get_private_profile_string(const char *section, const char *entry, const char *def, char *buffer, int buffer_len, char *file_name)
{ FILE *fp = fopen(file_name, "r");
char buff[MAX_LINE_LENGTH];
char *ep;
char t_section[MAX_LINE_LENGTH];
int len = strlen(entry);
if (!fp)
{
return();
}
sprintf(t_section, "[%s]", section); /* Format the section name */
/* Move through file 1 line at a time until a section is matched or EOF */
do
{
if (!read_line(fp, buff))
{
strncpy(buffer, def, buffer_len);
return(strlen(buffer));
}
}while (strcmp(buff, t_section));
/* Now that the section has been found, find the entry.
* Stop searching upon leaving the section's area. */
do
{
if (!read_line(fp, buff) || buff[] == '[') //130516 Willy modify '\0' to '[' for parser ini bug.
{
fclose(fp);
strncpy(buffer, def, buffer_len);
return(strlen(buffer));
}
}while (strncmp(buff, entry, len)); ep = strrchr(buff, '='); /* Parse out the equal sign */
do
{
ep++;
}while(!strncmp(ep, " ", )); //Remove the blank space /* Copy up to buffer_len chars to buffer */
strncpy(buffer, ep, buffer_len - );
buffer[buffer_len - ] = '\0';
fclose(fp); /* Clean up and return the amount copied */
return(strlen(buffer));
}
int Get_private_profile_hex(const char *section, const char *entry, int def, char *file_name)
{
char valBuf[], valBuf2[];
int data; memset(valBuf, , sizeof(valBuf));
memset(valBuf2, , sizeof(valBuf2)); sprintf(valBuf2, "0x%x", def);
Get_private_profile_string(section, entry, valBuf2, &valBuf[], sizeof(valBuf), file_name);
data = ;
sscanf(valBuf, "0x%x", &data);
return data;
} /*************************************************************************
* Function: Write_private_profile_string()
* Arguments: <char *> section - the name of the section to search for
* <char *> entry - the name of the entry to find the value of
* <char *> buffer - pointer to the buffer that holds the string
* <char *> file_name - the name of the .ini file to read from
* Returns: TRUE if successful, otherwise FALSE
*************************************************************************/
int Write_private_profile_string(const char *section, const char *entry, char *buffer, char *file_name)
{
FILE *rfp, *wfp;
char tmp_name[];
//Try to fix the issue that the MAX_PATH should be 256, not 80
char buff[MAX_LINE_LENGTH];
char t_section[MAX_LINE_LENGTH];
int len = strlen(entry);
tmpnam(tmp_name); /* Get a temporary file name to copy to */
sprintf(t_section, "[%s]", section); /* Format the section name */ rfp = fopen(file_name, "r");
if (!rfp) /* If the .ini file doesn't exist */
{
wfp = fopen(file_name, "w");
if (!wfp) /* then make one */
{
return();
}
fprintf(wfp, "%s\n", t_section);
fprintf(wfp, "%s=%s\n", entry, buffer);
fclose(wfp);
return();
} wfp = fopen(tmp_name, "w");
if (!wfp)
{
fclose(rfp);
return();
} /* Move through the file one line at a time until a section is
* matched or until EOF. Copy to temp file as it is read. */
do
{
if (!read_line(rfp, buff))
{
/* Failed to find section, so add one to the end */
fprintf(wfp, "\n%s\n", t_section);
fprintf(wfp, "%s=%s\n", entry, buffer);
/* Clean up and rename */
fclose(rfp);
fclose(wfp);
unlink(file_name);
rename(tmp_name, file_name);
return();
}
fprintf(wfp, "%s\n", buff);
}while (strcmp(buff, t_section)); /* Now that the section has been found, find the entry. Stop searching
* upon leaving the section's area. Copy the file as it is read
* and create an entry if one is not found. */
while ()
{
if (!read_line(rfp, buff))
{
/* EOF without an entry so make one */
fprintf(wfp, "%s=%s\n", entry, buffer);
/* Clean up and rename */
fclose(rfp);
fclose(wfp);
unlink(file_name);
rename(tmp_name, file_name);
return(); }
if (!strncmp(buff, entry, len) || buff[] == '\0')
{
break;
}
fprintf(wfp, "%s\n", buff);
} if (buff[] == '\0')
{
fprintf(wfp, "%s=%s\n", entry, buffer);
do
{
fprintf(wfp, "%s\n", buff);
}
while (read_line(rfp, buff));
}
else
{
fprintf(wfp, "%s=%s\n", entry, buffer);
while (read_line(rfp, buff))
{
fprintf(wfp, "%s\n", buff);
}
}
/* Clean up and rename */
fclose(wfp);
fclose(rfp);
unlink(file_name);
rename(tmp_name, file_name);
return();
} int Write_private_profile_int(const char *section, const char *entry, int data, char *file_name)
{
char valBuf[];
memset(valBuf, , );
sprintf(valBuf, "%d", data);
return Write_private_profile_string(section, entry, valBuf, file_name);
} unsigned long long Write_private_profile_longlong(const char *section, const char *entry, unsigned long long data, char *file_name)
{
char valBuf[];
memset(valBuf, , );
sprintf(valBuf, "%Lu", data);
return Write_private_profile_string(section, entry, valBuf, file_name);
}

ConfigFile.h

 #ifndef _CONFIGFILE_H_
#define _CONFIGFILE_H_ extern int Get_private_profile_int(const char *section, const char *entry, int def, char *file_name);
extern unsigned long long Get_private_profile_longlong(const char *section, const char *entry, unsigned long long def, char *file_name);
extern int Get_private_profile_string(const char *section, const char *entry, const char *def, char *buffer, int buffer_len, char *file_name);
extern int Get_private_profile_hex(const char *section, const char *entry, int def, char *file_name); extern int Write_private_profile_string(const char *section, const char *entry, char *buffer, char *file_name);
extern int Write_private_profile_int(const char *section, const char *entry, int data, char *file_name);
extern unsigned long long Write_private_profile_longlong(const char *section, const char *entry, unsigned long long data, char *file_name); #endif //_CONFIGFILE_H_

测试:

当前目录下Autoconfig.ini文件的内容为

测试源码:main.c

 #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <direct.h>
#include "GetConfig.h"
#define DEFAULT_INI_FILE "\\Autoconfig.ini" int main(int argc, char* argv[])
{
char ProductModel[];
char iniFile[];
char *buffer;
buffer = getcwd(NULL, );
strcpy(iniFile, buffer);
strcat(iniFile,DEFAULT_INI_FILE); Get_private_profile_string("Setting", "ProductModel", "SS", ProductModel, sizeof(ProductModel), iniFile);
printf("ProductModel:%s\n",ProductModel); unsigned char enExtendBlock = Get_private_profile_int("FwSetting", "EnExtendBlock", , iniFile);
printf("enExtendBlock:%d\n",enExtendBlock); int MPVersion = ;
Write_private_profile_int("Setting", "MPVersion", MPVersion, iniFile); sprintf(ProductModel,"ABCSFE!!221");
Write_private_profile_string("Setting", "ProductModel", ProductModel, iniFile); }

读取配置文件的C语言接口实现的更多相关文章

  1. Java 数据类型:集合接口Map:HashTable;HashMap;IdentityHashMap;LinkedHashMap;Properties类读取配置文件;SortedMap接口和TreeMap实现类:【线程安全的ConcurrentHashMap】

    Map集合java.util.Map Map用于保存具有映射关系的数据,因此Map集合里保存着两个值,一个是用于保存Map里的key,另外一组值用于保存Map里的value.key和value都可以是 ...

  2. Windows 服务多语言化时读取配置文件失败的问题。

    在Installer中,按一般读取配置文件的方法(ConfigurationManager.AppSettings["CultureName"])读取不到内容. 可以这样读取: v ...

  3. ServletContext 接口读取配置文件要注意的路径问题

    在建立一个maven项目时,我们通常把一些文件直接放在resource下面,在ServletContext中有getResource(String path)和getResourceAsStream( ...

  4. C语言 读取配置文件

    配置文件截图: 读取结果截图: 代码转自:http://www.tuicool.com/articles/Zb2iIn 附代码: // ReadConfig.cpp : 定义控制台应用程序的入口点. ...

  5. Python语言的configparser模块便捷的读取配置文件内容

    配置文件是在写脚本过程中经常会用到的,所以读取配置文件的模块configparser也非常重要,但是很简单. 首先我们的配置文件内容为: 这样的配置文件,[]里面的内容叫section,[]下面的内容 ...

  6. python接口测试之读取配置文件

    1.python使用自带的configparser模块用来读取配置文件,配置文件可以为.conf或.ini结尾 在使用前需要先安装该模块,使用pip安装即可 2.新建一个名为a.conf的配置文件 a ...

  7. Java 利用 ByteArrayOutputStream 和 ByteArrayInputStream 避免重复读取配置文件

    最近参与了github上的一个开源项目 Mycat,是一个mysql的分库分表的中间件.发现其中读取配置文件的代码,存在频繁多次重复打开,读取,关闭的问题,代码写的很初级,稍微看过一些框架源码的人,是 ...

  8. [转]SQLITE3 C语言接口 API 函数简介

    SQLITE3 C语言接口 API 函数简介 说明:本说明文档属作者从接触 SQLite 开始认识的 API 函数的使用方法, 由本人翻译, 不断更新. /* 2012-05-25 */ int sq ...

  9. 利用java反射机制 读取配置文件 实现动态类载入以及动态类型转换

    作者:54dabang 在spring的学习过程之中,我们能够看出通过配置文件来动态管理bean对象的优点(松耦合 能够让零散部分组成一个总体,而这些总体并不在意之间彼此的细节,从而达到了真正的物理上 ...

随机推荐

  1. python 1-10考试

  2. Python 栈和队列,双向队列

    # 栈 # 特点: 先进后出 class StackFullException(Exception): pass class StackEmptyException(Exception): pass ...

  3. 【Python】多进程1

    1.    进程定义: (1) 进程是一个实体.每个进程都有他自己的地址空间,一般包括文本区域.数据区域和堆栈.进程是线程的容器. (2) 进程是一个“执行中的程序” 2.    进程的特征: (1) ...

  4. http状态码301和302的区别

    1.官方的比较简洁的说明: 301 redirect: 301 代表永久性转移(Permanently Moved) 302 redirect: 302 代表暂时性转移(Temporarily Mov ...

  5. 基于区域的OSPF简单认证

    实验要求:掌握OSPF区域简单认证配置 拓扑如下: 配置如下: R1enable configure terminal interface s0/0/0ip address 192.168.1.1 2 ...

  6. Spring MVC — @RequestMapping原理讲解-1

    转载地址 :http://blog.csdn.net/j080624/article/details/56278461 为了降低文章篇幅,使得文章更目标化,简洁化,我们就不例举各种@RequestMa ...

  7. python base64 编解码,转换成Opencv,PIL.Image图片格式

    二进制打开图片文件,base64编解码,转成Opencv格式: # coding: utf-8 import base64 import numpy as np import cv2 img_file ...

  8. 【linux基础】linux远程登录

    可以用ssh命令行方式登录.对方需要开启ssh服务. 1. https://blog.csdn.net/zilaike/article/details/78922524 2. https://blog ...

  9. const 和let的本质区别

    在let和const之间,建议优先使用const,尤其是在全局环境,不应该设置变量,只应设置常量. const优于let有几个原因.一个是const可以提醒阅读程序的人,这个变量不应该改变:另一个是c ...

  10. set_uid set_gid stick_bit 软硬链接

    1.set_uid,里面的s权限   即运行一个命令时,普通用户临时拥有root权限 ( 增加和移除s权限 chmod u+s  file_name chmod u-s file_name 大S  和 ...