【C语言】《词典翻译》小程序
这是一款简单的“词典翻译”小程序,根据本地词库,简单实现,没有套壳,对于文件读写操作以及指针的精确掌握有着一定的帮助,希望读者能有所收获!其余我就不说太多了,代码有注释,词库文件在附件中,由于做测试使用,未添加太多词库,有时间爬一份完整的词库并将程序做成图形界面再发布。
使用方法
在其命令界面,根据提示输入单词(词库已录入),回车进行查找,其余均有提示,不再赘述。
/********************************************
* 1.创建结构体存储单词和翻译
* 2.读取单词,格式化存储对应的对空间中
* 3.单词查找
* 4.销毁堆空间
*******************************************/
//#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ONEK 1024
typedef struct dict
{
char *Word;
char *Trans;
}DICT;
DICT* list = NULL;
int GetWord()
{
//文件指针
FILE* fp = fopen("./dict.txt", "r");
if (!fp)
{
printf("词库加载失败\n");
return -1;
}
//开辟对应堆空间读取词库
list = (DICT*)malloc(sizeof(DICT) * 50);
//开辟临时空间存储读取词库内容
char* temp = (char*)malloc(sizeof(char) * ONEK);
int i = 0;
//读取词库文本加载到内存当中
while (!feof(fp))
{
memset(temp, 0, ONEK);
fgets(temp, ONEK, fp);
temp[strlen(temp) - 1] = 0; //temp末尾\n置为0
list[i].Word = malloc(sizeof(char) * strlen(temp) + 1);
if (!list[i].Word) return -2;
strcpy(list[i].Word, temp);
memset(temp, 0, ONEK);
fgets(temp, ONEK, fp);
temp[strlen(temp) - 1] = 0;
list[i].Trans = malloc(sizeof(char) * strlen(temp) + 1);
if (!list[i].Trans) return -2;
strcpy(list[i].Trans, &temp[6]); //去掉字符串开始Trans:(格式化字符串)
i++;
}
fclose(fp);
free(temp);
return i;
}
int SearchWord(int size)
{
char* word = (char*)malloc(sizeof(char) * 30);
char* trans = (char*)malloc(sizeof(char) * ONEK);
if (!word || !trans)
return -1;
while (1)
{
memset(word, 0, 30);
memset(trans, 0, ONEK);
printf("输入单词:[输入\":exit\"退出]\n");
//gets(word);
scanf("%s",word);
if (!strcmp(word, ":exit"))
{
printf("已退出查找\n");
break;
}
for (int i = 0; i < size; i++)
{
if (!strcmp(word, list[i].Word))
{
strcpy(trans, list[i].Trans);
break;
}
}
if (!strlen(trans))
printf("词库未录入\n");
else
printf("%s\n", trans);
}
free(word);
free(trans);
return 0;
}
int DestroySpace(int size)
{
if (!list)
return 0;
for (size_t i = 0; i < size; i++)
{
free(list[i].Word);
free(list[i].Trans);
}
free(list);
list = NULL;
return 0;
}
int main()
{
int size = GetWord();
if (!size)
printf("词库加载失败!\n");
SearchWord(size);
DestroySpace(size);
return 0;
}