您的位置:首页 > 编程语言 > C语言/C++

用c语言实现读取配置文件源码

2017-02-02 10:42 423 查看
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
#ip
ip:192.168.0.0.1
#port
port:8888
*/
/*读取配置文件*/
void test()
{
FILE *fp = fopen("config.txt", "r");
if (fp == NULL)
{
return;
}

char line[1024] = { 0 };
while (!feof(fp))
{
/*初始化line*/
memset(line, 0, 1024);
fgets(line, 1024, fp);
if (line[0] == '#')
{
continue;
}

int len = strlen(line);
/*查找冒号的位置*/
char *pos = strchr(line, ':');
if (pos == NULL)
{
continue;
}
char key[64] = { 0 };
char val[64] = { 0 };

/*消除不必要的换行*/
int offset = 1;
if (line[len - 1] == '\n')
{
offset = 2;
}

/*截取key,val值*/
strncpy(key, line, pos - line);
strncpy(val, pos + 1, line + len - offset - pos);

printf("%s -> %s\n", key, val);
}
}

int main()
{
test();
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  源码 字符串