文件按照键值对读取操作


//FileFunc.h

#ifndef FILEFUNC
#define FILEFUNC
#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct ConfigPair {
	char value[64];
	char key[64];
};
//获取有效行数
int getFileLines(const char* filePath);
//检测当前行是否有效信息
int isValidLines(const char* filePath);
//解析文件
void parseFile(const char* filePath, int lines, struct ConfigPair** configinfo);
//根据key获取value
const char* getByKey(const char* key, struct ConfigPair* configinfo, int lines);
//释放内存
void freeConfigPairPointer(struct ConfigPair** configinfo);

#endif


//FileFunc.cpp

#include "FileFunc.h"

int getFileLines(const char* filePath)
{
	FILE* file = fopen(filePath, "r");
	if (file == NULL) { return -1; }
	int lines = 0;
	char buf[1024] = { 0 };
	while (fgets(buf, 1024, file) != NULL) {
		if (isValidLines(buf)) {
			lines++;
		}
		memset(buf, 0, 1024);

	}
	fclose(file);
	return lines;
}

int isValidLines(const char* filePath)
{
	if (strchr(filePath, ':') == NULL) {
		return 0;
	}
	return 1;
}

void parseFile(const char* filePath, int lines, ConfigPair** configinfo)
{
	struct ConfigPair* pair = (struct ConfigPair*)malloc(sizeof(struct ConfigPair) * lines);
	if (pair == NULL) {
		return;
	}
	FILE* file = fopen(filePath, "r");
	if (file == NULL) {
		return;
	}
	char buf[1024] = { 0 };
	int index = 0;
	while (fgets(buf, 1024, file) != NULL) {
		if (isValidLines(buf)) {
			//信息有效
			memset(pair[index].key, 0, 64);
			memset(pair[index].value, 0, 64);
			char* pos = strchr(buf, ':');
			strncpy(pair[index].key, buf, pos - buf);
			strncpy(pair[index].value, pos + 1, strlen(pos + 1) - 1);
			index++;
		}
		memset(buf, 0, 1024);
	}
	*configinfo = pair;

}

const char* getByKey(const char* key, ConfigPair* configinfo, int lines)
{
	for (int i = 0; i < lines; ++i) {
		if (strcmp(key, configinfo[i].key) == 0) {
			return configinfo[i].value;

		}
	}
	return "";
}

void freeConfigPairPointer(ConfigPair** configinfo)
{
	if (*configinfo != NULL) {
		free(*configinfo);
		*configinfo = NULL;

	}
	return;
}


//main.cpp

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "FileFunc.h"

int main() {
	const char* filePath = "./text.txt";
	int lines = getFileLines(filePath);
	struct ConfigPair* configPair = NULL;
	parseFile(filePath, lines, &configPair);
	printf("根据key获取的value : %s", getByKey("lisi", configPair, lines));

	freeConfigPairPointer(&configPair);
	if (configPair == NULL) {
		printf("成功释放内存");
	}
	return 0;
}

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值