配置文件截图:

读取结果截图:

代码转自: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");
}

(完)

最新文章

  1. ubuntu remove mysql
  2. Maven使用笔记(四)pom.xml配置详解
  3. WEB网页插件 如何实现 选择上传图片路径 【高级问题】
  4. Ubuntu14.04搭建cocos2dx2.2.5开发环境(超级具体)
  5. configure: error: cannot find protoc, the Protocol Buffers compiler
  6. DataSet、DataTable、DataRow、DataColumn区别及使用实例
  7. 图解SSL/TLS协议(转)
  8. TextUtils
  9. Java实现随意切换VPN改变上网地区
  10. EF的join用法
  11. 解决flask的端口占用
  12. 11、OpenCV实现图像的灰度变换
  13. 阿里云服务器安装SQLServer本地无法远程访问
  14. POJ - 2635 E - The Embarrassed Cryptographer
  15. Java提高篇(转)
  16. ExtMail telnet 25端口号 不通
  17. AFNetWorking能做什么
  18. Redis Commands(1)
  19. ATM+购物商城
  20. java中一个简单的下载示例

热门文章

  1. 慢查询explan详解
  2. Java同步数据结构之LinkedBlockingQueue
  3. LC 955. Delete Columns to Make Sorted II
  4. IP拨号器
  5. C++ nth_element greater
  6. centos6.x一直停留在进度条的问题
  7. SpringBoot: 12.异常处理方式2(使用@ExceptionHandle注解)(转)
  8. Core Data概述(转)
  9. springMVC配置文件学习
  10. 工作采坑札记: 4. linux指定目录使用df和du的统计结果相差很大