一,查询
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 111104
struct INDEX
{
int start;
int end;
}index[27];
typedef struct DICT
{
char *word;
char *trans;
} DICT;
DICT * dict = NULL;
int GetFile(char *filename, char *wd)
{
FILE *in = fopen(filename, wd);
if (!in)
{
printf("can not open file!\n");
return -1;
}
dict = (DICT *)malloc(sizeof(DICT) * MAX);
char *buf = (char *)malloc(sizeof(char) * 1024);
int i = 0;
char ch = 'a';
int sum = 0;
int wodsindex = 0;
index[wodsindex].start = 0;
while (!feof(in))
{
memset(buf, 0, sizeof(char) * 1024);
fgets(buf, sizeof(char) * 1024, in);
int len = strlen(buf);
dict[i].word = (char *)malloc(sizeof(char) *len - 1);
memset(dict[i].word, 0, sizeof(char) *len - 2);
buf[strlen(buf) - 1] = '\0';
strcpy(dict[i].word, &buf[1]);
if (wodsindex == 26)
{
sum++;
index[26].end = sum;
}
else
{
if (buf[1] == ch)
{
sum++;
}
else
{
ch++;
index[wodsindex].end = sum - 1;
index[wodsindex + 1].start = sum;
wodsindex++;
sum++;
}
}
memset(buf, 0, sizeof(char) * 1024);
fgets(buf, sizeof(char) * 1024, in);
len = strlen(buf);
dict[i].trans = (char *)malloc(sizeof(char) * len - 6);
memset(dict[i].trans, 0, sizeof(char) *len - 6);
buf[strlen(buf) - 1] = '\0';
strcpy(dict[i].trans, &buf[6]);
i++;
}
for (i = 0; i < 26; i++)
{
printf("start = %d\n", index[i].start);
printf("end = %d\n", index[i].end);
}
free(buf);
fclose(in);
printf("加载完成。。。\n");
return 0;
}
int SearchWord(char *word, char *trans, int dex)
{
int i;
for (i = index[dex].start; i <= index[dex].end; i++)
{
if (!strcmp(word, dict[i].word))
{
strcpy(trans, dict[i].trans);
return 0;
}
}
return -1;
}
void DeshitySpase()
{
int i;
for (i = 0; i < MAX; i++)
{
if (dict[i].word != NULL)
{
free(dict[i].word);
dict[i].word = NULL;
}
if (dict[i].trans != NULL)
{
free(dict[i].trans);
dict[i].trans = NULL;
}
}
if (dict != NULL)
{
free(dict);
dict = NULL;
}
}
int main(int argc, char *argv[])
{
char *filename = "D:/FILE/dict.txt";
char *wd = "r";
GetFile(filename, wd);
char word[100], trans[100];
while (1)
{
scanf("%s", &word);
if (!strcmp(word, "comm==exit"))
{
break;
}
int len;
if (word[0] < 'z' && word > 'a')
{
len = SearchWord(word, trans, word[0] - 'a');
}
else
{
len = SearchWord(word, trans, word[0] - 26);
}
if (!len)
{
printf("%s\n", trans);
}
else
{
printf("没有找到了....\n");
}
}
DeshitySpase();
system("pause");
return EXIT_SUCCESS;
}