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

来源:互联网 发布:node socket.io聊天室 编辑:程序博客网 时间:2024/05/21 09:25
#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <stdlib.h>#include <string.h>/*#ipip:192.168.0.0.1#portport: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;}

0 0