//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;
}
文件按照键值对读取操作
最新推荐文章于 2024-05-29 18:15:57 发布