控制台电子词典

/*

#define _CRT_SECURE_NO_WARNINGS

为了在vs中编译

二次打开文件 运行时间会变长

*/

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX 111111
typedef struct dict
{
 char* key;
 char* content;
}dict;

//两次读取文件 一次获得行数,一次获得内容

int get_dict_size(FILE* pfile)
{
 if (pfile == NULL)
  return 0;
 int i = 0;
 char buf[2048];
 while (!feof(pfile))
 {
  fgets(buf, sizeof(buf), pfile);
  fgets(buf, sizeof(buf), pfile);
  i++;

 }
 return i;
}
//打开字典文件  读入内存  注意这里是二级指针
int open_dict(dict** p, const char* dict_filename)
{
 FILE* pfile = fopen(dict_filename, "r");
 if (pfile == NULL)
  return 0;
 int size = get_dict_size(pfile);
 if (size == 0)
 {
  return 0;
 }
 *p = (dict*)malloc(sizeof(dict) * size);
 memset(*p, 0, sizeof(dict) * size);
 fseek(pfile, 0L, SEEK_SET);//把文件指针重置到文件开头
 //*p = (dict*)malloc(sizeof(dict) * MAX);
 //memset(*p, 0, sizeof(dict) * MAX);
 dict* pD = *p;
 char buf[1024];
 size_t len = 0;
 int i = 0;
 while (!feof(pfile))
 {
  memset(buf, 0, sizeof(buf));
  fgets(buf, sizeof(buf), pfile);
  len = strlen(buf) + 1;
  //读入单词
  if (len > 0)
  {
   pD[i].key = (char*)malloc(len);
   memset(pD[i].key, 0, len);
   strcpy(pD[i].key, &buf[1]);//读入的是#word 所以从buf[1]开始copy

  }
  memset(buf, 0, sizeof(buf));
  fgets(buf, sizeof(buf), pfile);
  len = strlen(buf) + 1;
  if (len > 0)
  {
   pD[i].content = (char*)malloc(len);
   memset(pD[i].content, 0, len);
   strcpy(pD[i].content, &buf[6]);
  }
  i++;
 }
 fclose(pfile);
 return i;
}
//查找单词
int search_dict(const dict* p, const char* key, char* content)
{
 int i = 0;
 for (i = 0; i < MAX; 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);
   return 1;
  }
 }
 return 0;
}

//释放内存
void free_dict(dict* p, int size)
{
 int i = 0;
 for (i = 0; i < size; i++)
 {
  if (p[i].key)
   free(p[i].key);
  if (p[i].content)
   free(p[i].content);
 }
 free(p);
 p = NULL;
}
int main(int argc, char** argv)
{
 if (argc < 2)
 {
  printf("uage %s dict-filename ", argv[0]);
  return 0;
 }
 long start_ms = 0;
 long end_ms = 0;
 dict* p = NULL;
 start_ms = clock();
 int size = open_dict(&p, argv[1]);
 if (size == 0)
  return 0;
 end_ms = clock();
 printf("open_dict used: %ld ms ", end_ms - start_ms);
 char key[1024];
 char content[1024];
 while (1)
 {
  memset(key, 0, sizeof(key));
  memset(content, 0, sizeof(content));
  scanf("%s", key);
  if (strncmp(key, "command=exit", 12) == 0)
   break;
  start_ms = clock();
  if (search_dict(p, key, content))
  {
   printf("%s ", content);
  }
  else
  {
   printf("not find ");
  }
  end_ms = clock();
  printf("search dict used %ld ms ", end_ms - start_ms);
 }
 start_ms = clock();
 free_dict(p, size);
 end_ms = clock();
 printf("free dict used %ld ms ", end_ms - start_ms);
 return 0;
}

原文地址:https://www.cnblogs.com/countryboy666/p/11026725.html