最近工作中需要实现对文件的读取,删除,写入操作,就参考各路大佬的博文,自己使用c语言简单的实现了对文件的增删改查操作,主要实现如下
kv.c文件主要实现对文件的读,写,删除操作接口的实现,
一.
*函数名 : RemoveKeyValue
*函数功能描述 :如果指定文件存在key就删除key及value
*函数入参: char *fileName 文件名,char *key 键名
二.
三.
具体代码如下:
#include "kv.h"
void RemoveKeyValue(char *fileName,char *key)
{
char buf[ABUP_JSON_VALUE_SIZE] = "";
int isExist = 0;
int i = 0;
FILE *fp,*temp;
fp = fopen(fileName,"r");
temp = fopen("temp.txt","w");
if(fp == NULL)
{
printf("----------该文件不存在-----n");
goto finish;
}
fgets(buf,ABUP_JSON_VALUE_SIZE,fp);
do{
while(buf[i] == ' ')
{
i++;
}
if(strncmp(&buf[i],key,strlen(key))==0)
{
continue;
}
else
{
fputs(buf,temp);
}
}while(fgets(buf,ABUP_JSON_VALUE_SIZE,fp));
fclose(fp);
fclose(temp);
fp = fopen(fileName,"w");
temp = fopen("temp.txt","r");
while(1)
{
fgets(buf,sizeof(buf),temp);
if(feof(temp))
{
printf("删除成功n");
break;
}
fputs(buf,fp);
}
fclose(fp);
fclose(temp);
remove("temp.txt");
finish:
return ;
}
void WriteKeyValue(char *fileName,char *key,char *value)
{
char buf[ABUP_JSON_VALUE_SIZE] = "";
int i = 0;
int isExist = 0;
FILE *fp,*temp;
fp = fopen(fileName,"r");
if(fp == NULL)
{
fp = fopen(fileName,"w");
fprintf(fp,"%s = %sn",key,value);
fclose(fp);
printf("-------写入成功----------n");
}
else
{
temp = fopen("temp.txt","w");
fgets(buf,ABUP_JSON_VALUE_SIZE,fp);
do{
while(buf[i] == ' ')
{
i++;
}
if(strncmp(&buf[i],key,strlen(key))==0)
{
fprintf(temp,"%s = %sn",key,value);
isExist++;
}
else
{
fputs(buf,temp);
}
}while(fgets(buf,ABUP_JSON_VALUE_SIZE,fp));
if(isExist == 0)
{
fprintf(temp,"%s = %sn",key,value);
}
fclose(fp);
fclose(temp);
fp = fopen(fileName,"w");
temp = fopen("temp.txt","r");
while(1)
{
fgets(buf,sizeof(buf),temp);
if(feof(temp))
{
printf("-------写入成功----------n");
break;
}
fputs(buf,fp);
}
fclose(fp);
fclose(temp);
remove("temp.txt");
}
}
char* ReadValue(char *fileName,char *key)
{
char buf[ABUP_JSON_VALUE_SIZE] = "";
int i = 0;
char *value = NULL;// value
int valueLen = 0;//value长度
char *valueBuf = NULL;
int isExist = 0;
FILE *fp;
fp = fopen(fileName,"r");
if(fp == NULL)
{
goto finish;
}
fgets(buf,ABUP_JSON_VALUE_SIZE,fp);
do{
while(buf[i] == ' ')
{
i++;
}
if(strncmp(&buf[i],key,strlen(key))==0)
{
value = strstr(&buf[i],"=")+1;
valueLen = strlen(value);
valueBuf = (char*)malloc(sizeof(char)*(valueLen+1));
i = 0;
while(i

