#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
typedef struct
{
char *key;
char *content;//用堆了,省内存
}dict;
//打开字典文件,并读取文件内容
int open_dict(dict **p,const char *dict_filename)
{
FILE *pfile = fopen(dict_filename,"r");
if (pfile == NULL)return 0;
*p = (dict*)malloc(sizeof( dict));//固定分配MAX大小内存
memset(*p,0,sizeof(dict));//将分配内存初始化为0
char buf[1024] = {0};
size_t len = 0;
int i = 0;//计数器
while(!feof(pfile))//循环读取文件,知道文件结尾
{
memset(buf,0,sizeof(buf));
fgets(buf,sizeof(buf),pfile);
len = strlen(buf);
if(len > 0)
{
(*p)[i].key = (char *)malloc(len);//把key值输入
memset((*p)[i].key,0,len);
strcpy((*p)[i].key,&buf[1]);//第一个字为#,不录入
}
memset(buf,0,sizeof(buf));
fgets(buf,sizeof(buf),pfile);
len = strlen(buf);
if (len > 0)
{
(*p)[i].content = (char*)malloc(len);
memset((*p)[i].content,0,len);
strcpy((*p)[i].content,&buf[6]);//前6个字节不录入
}
i++;
*p = ( dict *)realloc(*p,(1 + i) *sizeof(dict));//动态增加内存!
memset(*p + i,0,sizeof(dict));//清空最后一个
}
fclose(pfile);
return i;
}
int search_dict(const dict *p,int size,const char *key,char *content)
{//通过key值,返回content的内容,并用01表示是否成功
int i = 0;
for (int i = 0; i < size; ++i)
{
if ((p[i].key == NULL) || (p[i].content == NULL)) continue;
if (strncmp(p[i].key,key,strlen(key)) == 0)
{
strcpy(content,p[i].content);//strcpy是两个都是char *类型
return 1;
}
}
return 0;
}
void free_dict(dict *p,int size)//循环释放堆内存
{
for (int i = 0; i < size; ++i)
{
if (p[i].key)
free(p[i].key);
if (p[i].content)
free(p[i].content);
}
free(p);
}
int main(int argc, char const *argv[])
{
if (argc < 2)
{
printf("usage: %s dict filename\n",argv[0] );
return 0;
}
long start_ms = 0;
long end_ms = 0;
dict *p = NULL;
start_ms = clock();
int dict_size = open_dict(&p,argv[1]);
if (dict_size == 0)
return 0;
end_ms = clock();
printf("open_dict used %ld ms\n",end_ms - start_ms );
char key[2048];
char content[2048];
while(1)
{
memset(key,0,sizeof(key));
memset(content,0,sizeof(content));
scanf("%s",key);//输入key值
if (strncmp(key,"command=exit",12)==0)
{
break;
}
start_ms = clock();
if (search_dict(p,dict_size,key,content))
{
printf("%s\n",content );
}else
{
printf("not found\n");
}
end_ms = clock();
printf("search_dict used %ld ms\n",end_ms - start_ms);
}
start_ms = clock();
free_dict(p,dict_size);
end_ms = clock();
printf("free_dict used %ld ms\n",end_ms - start_ms );
return 0;
}
效果图:
1.png
PS:电脑一般不自配gcc编译,可以用VS或者VC编译
网友评论