对一个配置文件的操作
其中涉及了两头堵模型和怎么在原有位置上修改文件内容,和一些常规文件的操作。
函数功能:1.对一个文件按给的key值,读取到它的value。
2.对一个文件做写操作,如果文件里面没有key,将key和它的value值加在文件的末尾,如果有的话,修改它的value
3.要想在原有位置修改文件,先读入到内存,修改,然后再修改。
4.文件大小不能超过8k
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string>
#define size 8*1024
/*
函数功能:1.对一个文件按给的key值,读取到它的value。
2.对一个文件做写操作,如果文件里面没有key,将key和它的value值加在文件的末尾,如果有的话,修改它的value
*/
char * deal_space(char *p)//两头堵模型 去掉空格
{
int begin = 0;
int end = strlen(p)-1;
int n = 0;
char *buf1 = (char*)malloc(30);
while (isspace(p[begin])&&p[begin]!=0)
{
begin++;
}
n = end - begin + 1;
strncpy(buf1, p + begin,n);
buf1[n] = 0;
return buf1;
}
int show(void)//界面的实现
{
printf("=============================\n");
printf("1 写配置文件\n");
printf("2 读配置文件\n");
printf("3 清屏\n");
printf("4 退出\n");
printf("=============================\n");
int i;
printf("cmd:");
scanf("%d",&i);
return i;
}
int write_file(void)//向配置文件写特定的文件
{
FILE *fp = NULL;
printf("请输入key:");
char key[4] = { 0 };
scanf("%s", &key);
printf("请输入value:");
char value[30] = {0};
scanf("%s", &value);
fp = fopen("./01.txt", "r+");
if (fp == NULL)
{
perror(" file fopen");
system("pause");
return -1;
}
fseek(fp, 0, SEEK_SET);
long file_size = ftell(fp);
if (file_size>size)
{
printf("文件内容大于8K");
goto End;
}
rewind(fp);
int flag=0;
char linear_buf[30] = { 0 };
char buf[size] = {0};
char tmp[1024] = { 0 };
while (!feof(fp))
{
fgets(linear_buf, sizeof(linear_buf), fp);
if (strstr(linear_buf, key)!= NULL)
{
sprintf(tmp, "%s=%s\n",key,value);
strcat(buf, tmp);
flag = 1;
}
else
{
strcat(buf, linear_buf);
}
}
if (flag==1)
{
if (fp != NULL)
{
fclose(fp);
fp = NULL;
}
fp = fopen("./01.txt", "w+");
if (fp == NULL)
{
perror(" file fopen");
system("pause");
}
fputs(buf,fp);
goto End;
}
else
{
fprintf(fp, "%s=%s\n", key, value);
goto End;
}
End: if (fp != NULL)
{
fclose(fp);
fp = NULL;
}
return 0;
}
int read_file(void) //读配置文件的文件
{
FILE *fp = NULL;
printf("请输入key:");
char str[10] = {0};
scanf("%s", &str);
fp = fopen("./01.txt","r+");
if (fp == NULL)
{
perror(" file fopen");
system("pause");
return -1;
}
char ch[30] = {0};
char *buf = (char *)malloc(sizeof(char)* 30);
while (!feof(fp))
{
char *p = fgets(ch, sizeof(ch), fp);
char *tem = strstr(ch,str);
if (tem != NULL)
{
tem = tem + strlen(str) + 1;
strcpy(buf, tem);
buf = deal_space(buf);
int len = strlen(buf);
printf(" %s对应的value: %s , 长度为%d", str, buf, len);
}
}
if (fp != NULL)
{
fclose(fp);
fp = NULL;
}
if (buf!=NULL)
{
free(buf);
buf = NULL;
}
return 0;
}
int clear_screen(void)
{
return 0;
}
int exit_file(void)
{
return 0;
}
int main(void)
{
while (1)
{
int ret=show();
switch (ret)
{
case 1:write_file(); break;
case 2:read_file(); break;
case 3:clear_screen(); break;
case 4:break;
default:break;
}
system("pause");
}
return 0;
}
界面图:
原来的文件:
写文件操作之后的图:
读文件操作图: