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

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. [转]自然语言处理中的Attention Model:是什么及为什么

    自然语言处理中的Attention Model:是什么及为什么 https://blog.csdn.net/malefactor/article/details/50550211 /* 版权声明:可以 ...

  2. Linux大文件分割splite

    /********************************************************************** * Linux大文件分割splite * 说明: * 编 ...

  3. Refused to execute inline event handler because it violates the following Content Security Policy directive: "xxx". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...')

    /********************************************************************************* * Refused to exec ...

  4. multi-thread debug

    1.不要去解锁一个未被加锁的mutex锁: 2.不要一个线程中加锁而在另一个线程中解锁: 3.使用mutex锁用于保护临界资源,严格按照“加锁-->写入/读取临界资源-->解锁”的流程执行 ...

  5. Java中的Arrays类使用详解

    首先先创建一个打印数组的方法,方便后面直接使用 public static void output(int []a) { for(int i=0;i<a.length;i++) { System ...

  6. IDA*(以The Ratotion Game POJ--2286 UVa1343为例)

    IDA*算法实质就是迭代加深搜索和A*算法的结合,通过迭代加深搜索来寻找答案,借由预估函数h()来进行估计与剪枝. 本题主框架如下: ;;maxd++) { ,maxd)) break; } 由1开始 ...

  7. hdu3338 Kakuro Extension 最大流

    If you solved problem like this, forget it.Because you need to use a completely different algorithm ...

  8. Python 3.5 in win10 pip install Orange3

    http://www.lfd.uci.edu/%7Egohlke/pythonlibs/ 下载Orange3 以及 依赖包 注意网页上标出的Orange 的依赖,以及 https://github.c ...

  9. web项目【3】

    前端代码: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.a ...

  10. 【mybatis源码学习】利用maven插件自动生成mybatis代码

    [一]在要生成代码的项目模块的pom.xml文件中添加maven插件 <!--mybatis代码生成器--> <plugin> <groupId>org.mybat ...