读取配置文件的C语言接口实现
在一些场合,需要对一些配置文件进行读取,去设置软件的参数,自己实现了一些接口函数,以供以后使用。
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语言接口实现的更多相关文章
- Java 数据类型:集合接口Map:HashTable;HashMap;IdentityHashMap;LinkedHashMap;Properties类读取配置文件;SortedMap接口和TreeMap实现类:【线程安全的ConcurrentHashMap】
Map集合java.util.Map Map用于保存具有映射关系的数据,因此Map集合里保存着两个值,一个是用于保存Map里的key,另外一组值用于保存Map里的value.key和value都可以是 ...
- Windows 服务多语言化时读取配置文件失败的问题。
在Installer中,按一般读取配置文件的方法(ConfigurationManager.AppSettings["CultureName"])读取不到内容. 可以这样读取: v ...
- ServletContext 接口读取配置文件要注意的路径问题
在建立一个maven项目时,我们通常把一些文件直接放在resource下面,在ServletContext中有getResource(String path)和getResourceAsStream( ...
- C语言 读取配置文件
配置文件截图: 读取结果截图: 代码转自:http://www.tuicool.com/articles/Zb2iIn 附代码: // ReadConfig.cpp : 定义控制台应用程序的入口点. ...
- Python语言的configparser模块便捷的读取配置文件内容
配置文件是在写脚本过程中经常会用到的,所以读取配置文件的模块configparser也非常重要,但是很简单. 首先我们的配置文件内容为: 这样的配置文件,[]里面的内容叫section,[]下面的内容 ...
- python接口测试之读取配置文件
1.python使用自带的configparser模块用来读取配置文件,配置文件可以为.conf或.ini结尾 在使用前需要先安装该模块,使用pip安装即可 2.新建一个名为a.conf的配置文件 a ...
- Java 利用 ByteArrayOutputStream 和 ByteArrayInputStream 避免重复读取配置文件
最近参与了github上的一个开源项目 Mycat,是一个mysql的分库分表的中间件.发现其中读取配置文件的代码,存在频繁多次重复打开,读取,关闭的问题,代码写的很初级,稍微看过一些框架源码的人,是 ...
- [转]SQLITE3 C语言接口 API 函数简介
SQLITE3 C语言接口 API 函数简介 说明:本说明文档属作者从接触 SQLite 开始认识的 API 函数的使用方法, 由本人翻译, 不断更新. /* 2012-05-25 */ int sq ...
- 利用java反射机制 读取配置文件 实现动态类载入以及动态类型转换
作者:54dabang 在spring的学习过程之中,我们能够看出通过配置文件来动态管理bean对象的优点(松耦合 能够让零散部分组成一个总体,而这些总体并不在意之间彼此的细节,从而达到了真正的物理上 ...
随机推荐
- 有两艘船需要装运的n箱货物,第一艘船的载重量是c1,第二艘船的载重量是c2,wi是货箱i的重量,且w1+w2+……+wn<=c1+c2
(1) 问题描述: 有两艘船和需要装运的n个货箱,第一艘船的载重量是c1,第二艘船的载重量是c2,wi是货箱的质量,且w1+w2+...+wn <= c1+c2. 希望确定是否有一 ...
- 【转载】 5G+边缘计算,着眼可见的未来 【边缘计算】
原文地址: https://www.cnblogs.com/upyun/p/10641489.html ------------------------------------------------ ...
- Subsequence Count 2017ccpc网络赛 1006 dp+线段树维护矩阵
Problem Description Given a binary string S[1,...,N] (i.e. a sequence of 0's and 1's), and Q queries ...
- selenium 定位无标签的元素
转载需注明出处. 如: ::before 伪元素xpath css_selector. id. class_name各种定位失效,可以选择用, .get_attribute('innerHTML')方 ...
- WCF 添加服务引用 HTTP 请求已超过为 00:00:00 分配的超时。为此操作分配的时间可能是较长超时
今天在用公司的笔记本引用WCF的时候,处于一直等待的过程,一直在下载信息,一直等了很长时间,弹出了一个消息 下载“http://ip:8085/xxxxx/xxxxx/mex/$metadata”时出 ...
- flask连接mysql数据库
from flask import Flask from flask_sqlalchemy import SQLAlchemy import pymysql pymysql.install_as_My ...
- lesson4Embedding-fastai
dense layer:mnist识别中,需要十组dense权重矩阵来计算这十个输出内容,conv矩阵每一个元素乘以另一个矩阵的元素并相加,得到一个值,最后加上sigmoid(softmax在二元情况 ...
- 20155208徐子涵 2016-2017-2 《Java程序设计》第5周学习总结
20155208徐子涵 2016-2017-2 <Java程序设计>第5周学习总结 教材学习内容总结 第八章 异常处理 8.1 语法与继承结构 Java中所有错误都会被打包为对象,运用tr ...
- Beta周第7次Scrum会议(11/16)【王者荣耀交流协会】
一.小组信息 队名:王者荣耀交流协会 小组成员 队长:高远博 成员:王超,袁玥,任思佳,王磊,王玉玲,冉华 小组照片 二.开会信息 时间:2017/11/16 17:03~17:17,总计14min. ...
- 2017.7.21 python statvfs方法读取磁盘容量
实地代码 [maintenance@localhost ~]$ python Python 2.7.5 (default, Nov 6 2016, 00:28:07) [GCC 4.8.5 20150 ...