第1个回答 推荐于2016-11-09
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <locale.h>
#include <windows.h>
#define MAX_LEN 30
#define DICTIONARY "C://Dictionary.dat"
typedef struct mymay mapping;
struct mymay{
wchar_t ch[MAX_LEN];
wchar_t en[MAX_LEN];
mapping * next;
};
int addNew(wchar_t* en, wchar_t* ch, mapping* head) {
mapping *tmp = head;
if (!head) {
return 0;
}
while(tmp->next) {
if (wcscmp(tmp->ch, ch) == 0 && wcscmp(tmp->en, en) == 0) {
return 1;
}
tmp = tmp->next;
}
tmp->next = (mapping *)malloc(sizeof(mapping));
if (!tmp->next) {
return 1;
}
wcscpy(tmp->next->ch, ch);
wcscpy(tmp->next->en, en);
tmp->next->next = NULL;
return 0;
}
int createHead(wchar_t* en, wchar_t* ch, mapping **head){
*head = (mapping *)malloc(sizeof(struct mymay));
if (!(*head)) {
printf("aaa1\n");
return 1;
}
wcscpy((*head)->ch, ch);
wcscpy((*head)->en, en);
(*head)->next = NULL;
return 0;
}
int destroyList(mapping *head) {
mapping *tmp = NULL;
while(head) {
tmp = head;
head = head->next;
free(tmp);
}
return 0;
}
wchar_t* searchList(wchar_t target[], mapping *head){
mapping *tmp = head;
if (head != NULL) {
while(tmp) {
if (wcscmp(tmp->ch, target) == 0)
return tmp->en;
else if (wcscmp(tmp->en, target) == 0)
return tmp->ch;
tmp = tmp->next;
}
}
return NULL;
}
int saveDictionary(mapping *head){
FILE* fp;
mapping *tmp = head;
if ((fp = fopen(DICTIONARY, "w")) == NULL){
printf("Can not open dictionary file.\n");
return 1;
}
while (tmp) {
fwrite(tmp,sizeof(mapping),1,fp);
tmp = tmp->next;
}
fclose(fp);
return 0;
}
int loadDictionary(mapping **head){
FILE* fp;
mapping tmp;
if ((fp = fopen(DICTIONARY, "r")) == NULL){
return 1;
}
while(fread(&tmp,sizeof(mapping),1,fp)==1) {
if(!*head) {
createHead(tmp.en, tmp.ch, head);
} else {
addNew(tmp.en, tmp.ch, *head);
}
}
fclose(fp);
return 0;
}
int main(){
mapping *head = NULL;
wchar_t s1[MAX_LEN];
wchar_t s2[MAX_LEN];
wchar_t* ret = NULL;
int select;
setlocale(LC_ALL, "Chinese");
loadDictionary(&head);
for(;;) {
printf("**************MENU**************\n");
printf("1.Search words.\n");
printf("2.Insert words.\n");
printf("3.bye.\n");
printf("**************MENU**************\n");
scanf("%d",&select);
switch(select) {
case 1:
system("CLS");
printf("************1.Search words**********\n");
printf("Input the word:\n");
scanf("%ls",&s1);
if (ret = searchList(s1, head)) {
wprintf(L"The Translation is [%s].\nany key to continue\n", ret);
} else {
printf("Can not find the Translation.\nany key to continue\n");
}
getch();
break;
case 2:
system("CLS");
printf("************2.Insert words.**********\n");
printf("Input the English:\n");
scanf("%ls",s1);
printf("Input the Chinese:\n");
scanf("%ls",s2);
if (!head) {
createHead(s1, s2, &head);
} else if (!addNew(s1, s2, head)) {
printf("Insert success!\nany key to continue\n");
} else {
printf("Insert failed!\nany key to continue\n");
}
getch();
break;
case 3:
goto END;
}
system("CLS");
}
END:
saveDictionary(head);
return 0;
}
我之前写过的,除了你说的功能外,还有录入功能本回答被提问者采纳