加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
conf.c 3.23 KB
一键复制 编辑 原始数据 按行查看 历史
yfeic 提交于 2020-03-09 17:07 . 2020000309
/*
* Copyright (C) 2019 All rights reserved.
*
* FileName :conf.c
* Author :yuefei.Chen
* Email :yfei777@outlook.com
* Date :2019年03月21日
* Description :
*/
#include "conf.h"
#define FLEN 8192
//去掉字符串前后的空格,并输出。
void trim(char *strin, char *strout) {
char *start, *end, *tmp;
tmp = strin;
while (*tmp == ' ') {
++tmp;
}
start = tmp;
tmp = strin + strlen(strin) - 1;
while (*tmp == ' ') {
--tmp;
}
end = tmp;
for (strin = start; strin <= end;) {
*strout++ = *strin++;
}
*strout = '\0';
}
/*
* 将key=value格式的字符串按照=切割,如果key与指定值相同输出value值。
*/
void getValue(char *keyAndValue, const char *key, char *value) {
char tokey[1024]={0},kav[1024]={0};
strcpy(kav,keyAndValue);
trim(strtok(kav,"="),tokey);
if (strcmp(tokey,key)==0) {
trim(strtok(NULL,"="),value);
}
return;
}
/*
* 将key=value写入文件
*/
int writeCFG(const char *filename, const char *key, const char *value) {
FILE *pf = NULL;
long fsize = 0;
int exit = 0;
int reg = 0;
char ftemp[FLEN] = { 0 }, fline[1024] = { 0 }, tfline[1024] = { 0 },
tokey[1024] = { 0 }, *fp;
pf = fopen(filename, "r+");
if (pf == NULL) {
pf = fopen(filename, "w+");
}
fseek(pf, 0, SEEK_END);
fsize = ftell(pf);
if (fsize > FLEN) {
perror("size of file can not over 8k");
reg = -1;
goto end;
}
fseek(pf, 0, SEEK_SET);
fgets(fline,1024,pf);
while (!feof(pf)) {
if (strcmp(fline, "\n") == 0 || strcmp(fline, "") == 0) {
fgets(fline,1024,pf);
continue;
}
strcpy(tfline, fline);
trim(strtok(tfline, "="), tokey);
if (strcmp(key, tokey) == 0) {
if (exit == 0) {
exit = 1;
sprintf(fline, "%s = %s\n", key, value);
strcat(ftemp, fline);
}
}else{
strcat(ftemp, fline);
}
fgets(fline,1024,pf);
}
if (exit != 1) {
sprintf(fline, "%s = %s\n", key, value);
strcat(ftemp, fline);
}
if (pf != NULL) {
fclose(pf);
pf = fopen(filename, "w+");
fp = (char *) malloc(sizeof(char) * strlen(ftemp));
strcpy(fp, ftemp);
fputs(fp, pf);
if (fp != NULL) {
free(fp);
}
}
end: if (pf != NULL) {
fclose(pf);
}
return reg;
}
/*
* 从文件中读取指定key值相同行的value值。
*/
void readCFG(const char *filename, const char *key, char **value) {
FILE *pf = NULL;
char line[1024] = { 0 }, vtemp[1024] = { 0 };
pf = fopen(filename, "r"); //以只读方式打开
if (pf==NULL) {
return;
}
fgets(line, 1024, pf);
while (!feof(pf)) {
getValue(line, key, vtemp);
if (strlen(vtemp) != 0)
break;
fgets(line, 1024, pf);
}
if (strlen(vtemp) != 0) {
*value = (char *) malloc(sizeof(char) * strlen(vtemp));
memset(*value,0,strlen(vtemp));
strncpy(*value, vtemp,strlen(vtemp)-1);
} else
*value = NULL;
if (pf != NULL)
fclose(pf);
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化