有一个config.txt文件内容如下:
要求:输出有效信息,输入:左边的属性(key),屏幕能输出右边的value
/*
config.h
*/
#pragma once
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct Hero
{
char key[64];
char value[64];
};
//获取有效行数
int getFileLine(char* filename);
//判断当前行是否有效
int isValidLine(char* str);
//解析文件
void parseFile(char* filename,struct Hero** hero,int line);
//根据索引值获取 实值
char* toValue(char* str,struct Hero* hero,int line);
//释放信息
void freeSpace(struct Hero* info);
/*
config.c
*/
#include"config.h"
//获取有效行数 + 解析文件
int getFileLine(char* filename)
{
int line = 0;
char buff[1024] = {0};
FILE* f_read = fopen(filename,"r");
if(f_read == NULL)
{
return -1;
}
while(!feof(f_read))
{
fgets(buff,1024,f_read);
if(isValidLine(buff))
{
line ++;
}
}
return line;
}
//判断当前行是否有效
int isValidLine(char* str)
{
if(str[0] == '\0' || str[0] == ' ' || strchr(str,':') == NULL)
{
return 0;
}
return 1;
}
//解析文件
void parseFile(char* filename,struct Hero** hero,int line)
{
int index = 0;
char buff[1024] = { 0 };
//char* pos = strchr(buff,':'); //pos 代表冒号所在位置
char* pos = (char*)malloc(sizeof(char));
struct Hero* info = (struct Hero*)malloc(sizeof(struct Hero) * line);
FILE* f_read = fopen(filename,"r");
if(f_read == NULL)
{
return;
}
while(fgets(buff,1024,f_read)!=NULL)
{
//fgets(buff,1024,f_read);
//有效信息才会被解析
if(isValidLine(buff))
{
//清空操作
memset(info[index].key,0,64);//将key域清0
memset(info[index].value,0,64);
pos = strchr(buff,':'); //pos 代表冒号所在位置
strncpy(info[index].key,buff,pos - buff);
strncpy(info[index].value,pos + 1,strlen(pos + 1) - 1);//减1是因为每行以'\n'结尾,打印的时候会多输出一行换行
printf("key = %s",info[index].key);
printf("value = %s\n",info[index].value);
index ++;
}
memset(buff,0,1024);
}
*hero = info;
}
//根据索引值获取 实值
char* toValue(char* str,struct Hero* hero,int line)
{
int i;
for(i = 0;i < line; i++)
{
if(strcmp(str,hero[i].key) == 0)
{
return hero[i].value ;
}
}
return NULL;
}
//释放信息
void freeSpace(struct Hero* info)
{
if(info != NULL)
{
free(info);
info = NULL;
}
}
/*
test.c
*/
#include<stdio.h>
#include<string.h>
#include"config.h"
void test01()
{
int line;
char* filepath = "./config.txt";
struct Hero* hero = NULL;
line = getFileLine(filepath);
printf("有效行数为:%d\n",line);
//测试 根据key 访问 value
parseFile(filepath,&hero,line);
printf("heroId = %s\n",toValue("heroId",hero,line));
printf("heroName = %s\n",toValue("heroName",hero,line));
printf("heroAtk = %s\n",toValue("heroAtk",hero,line));
printf("heroDef = %s\n",toValue("heroDef",hero,line));
printf("heroInfo = %s\n",toValue("heroInfo",hero,line));
}
int main()
{
test01();
return 0;
}
结果如果读出来中文是乱码,可以检查下读取的文件是不是ANSI格式。