头文件:Cfg.h
#ifndef CFG_SET_GET_H #define CFG_SET_GET_H #ifdef __cplusplus extern "C" { #endif int setCfg(char * filename, char *key, char *value); int getCfg(char * filename, char *key, char *value); #ifdef __cplusplus } #endif #endif // !CFG_SET_GET_H
实现文件:Cfg.c
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #define MaxLineSize 2048 #define MaxKeySize 64 int setCfg(char * filename, char *key, char *value) { //返回值 文件总长度 int rv = 0, length = 0,isSet = 0; //文件指针 FILE * fp = NULL; //暂时保存每行值 char stringBuf[MaxLineSize]; char *p; //缓存文字 char logBuffer[2048 * 8] = { 0 }; //缓存当前行的key char cachekey[MaxKeySize]; //临时辅助指针 char * vbegin = NULL, *vend = NULL, *vtemp = NULL; memset(cachekey, 0, MaxKeySize); if (filename == NULL || key == NULL || value == NULL) { printf("PARAM IS ERROR..."); rv = 1; goto End; } fp = fopen(filename, "r+"); if (fp == NULL) { printf("FILE OPEN ERROR..."); rv = 2; goto End; } //移动到最后 fseek(fp, 0L, SEEK_END); //获取总长度 length = ftell(fp); if (length > 2048*8) { printf("FILE IS TOO BIG TO OPERATE..."); rv = 3; goto End; } //移动到最开始 fseek(fp, 0L,SEEK_SET); while (!feof(fp)) { //初始化值 memset(stringBuf, 0, 2048); //获取一行 p = fgets(stringBuf, 2048, fp); //没有匹配到字符 则继续 if (p == NULL) { break; } //保存=字符的指针 vtemp = strchr(stringBuf, '='); //没有匹配到=字符 则继续 if (vtemp == NULL) { continue; } //没有匹配到key字符 则继续 vtemp = p; //去除key前的空字符 while (1) { //直到不为空 if (*vtemp == ' ') { vtemp++; continue; } if (*vtemp == '=') { printf("KEY IS EMPTY... "); rv = 4; goto End; } vbegin = vtemp; break; } //去除key后的空字符 while (1) { if (*vtemp != ' ' && *vtemp != '=') { vtemp++; continue; } vend = vtemp; break; } memcpy(cachekey, vbegin, vend - vbegin); *(cachekey + (vend - vbegin)) = '