C语言 读取配置文件
2024-10-06 15:47:33
配置文件截图:
读取结果截图:
代码转自:http://www.tuicool.com/articles/Zb2iIn
附代码:
// ReadConfig.cpp : 定义控制台应用程序的入口点。
//
//#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h> struct configItem
{
char key[];
char value[];
}; configItem configList[] = {
{"ip", },
{"port", },
{"line", }
}; /*
* 这个函数是对给定的一个字符串寻找以等号分开的键值对
* src -- 源字符串
* key -- 键
* value -- 值
*/
int strkv(char *src, char *key, char *value)
{
char *p, *q;
int len;
p = strchr(src, '=');//p找到等号
q = strchr(src, '\n');//q找到换行 //如果有等号有换行
if (p != NULL && q != NULL)
{
*q = '\0'; //将换行设置为字符串结尾
strncpy(key, src, p-src); //将等号前的内容拷入key中
strcpy(value, p+); //将等号后的内容拷入value中,跳过等号所以p需要加1
return ;
}
return ;
} /*
* 读取配置函数
*
*/
void Config(char * configFilePath, struct configItem* configVar, int configNum)
{
int i;
FILE * pfile;
char buf[] = ""; //缓冲字符串
char key[] = ""; //配置变量名
char value[] = ""; //配置变量值 //打开配置文件
pfile = fopen(configFilePath, "r"); if (pfile == NULL)
{
printf("配置文件打开失败!\n");
exit(-);
} //依次读取文件的每一行
while (fgets(buf, , pfile))
{
//读取键值对
if (strkv(buf, key, value))
{
//读取成功则循环匹配数组
for (i = ; i < configNum; i++)
{
//名称相等则匹配成功,拷贝value值
if (strcmp(key, configVar[i].key) == )
{
strcpy(configVar[i].value, value);
}
}
//key字符串在strkv函数内部没有给结束符'\0',需要这里重置一下
//value在strkv中已经给了结束符'\0'
memset(key, , strlen(key));
} }
fclose(pfile);
} void main()
{
int i;
//读取配置文件
Config("C:\\config.txt",
configList,
sizeof(configList)/sizeof(struct configItem)
); for (i = ; i < sizeof(configList)/sizeof(struct configItem); i++)
{
printf("%s=%s \n", configList[i].key, configList[i].value);
}
system("pause");
}
(完)
最新文章
- ubuntu remove mysql
- Maven使用笔记(四)pom.xml配置详解
- WEB网页插件 如何实现 选择上传图片路径 【高级问题】
- Ubuntu14.04搭建cocos2dx2.2.5开发环境(超级具体)
- configure: error: cannot find protoc, the Protocol Buffers compiler
- DataSet、DataTable、DataRow、DataColumn区别及使用实例
- 图解SSL/TLS协议(转)
- TextUtils
- Java实现随意切换VPN改变上网地区
- EF的join用法
- 解决flask的端口占用
- 11、OpenCV实现图像的灰度变换
- 阿里云服务器安装SQLServer本地无法远程访问
- POJ - 2635 E - The Embarrassed Cryptographer
- Java提高篇(转)
- ExtMail telnet 25端口号 不通
- AFNetWorking能做什么
- Redis Commands(1)
- ATM+购物商城
- java中一个简单的下载示例
热门文章
- 慢查询explan详解
- Java同步数据结构之LinkedBlockingQueue
- LC 955. Delete Columns to Make Sorted II
- IP拨号器
- C++ nth_element greater
- centos6.x一直停留在进度条的问题
- SpringBoot: 12.异常处理方式2(使用@ExceptionHandle注解)(转)
- Core Data概述(转)
- springMVC配置文件学习
- 工作采坑札记: 4. linux指定目录使用df和du的统计结果相差很大