C语言(文件与IO)---- 实现电子英语词典
所需要的词典文本文件
链接 :https://pan.baidu.com/s/1lVweza25PmrcRV-wYeHdwQ
提取码:0cop
将词典文本文件放在代码同个文件夹下
整体的设计流程图
实现代码
dictionary.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 2048
typedef struct Node{
char *wd;
char *tran;
struct Node *next;
}Node;
//把字典加载进入内存
Node *loadDictionary() {
Node *head = NULL;
char buff[MAXLEN];
FILE *file = fopen("./dictionary.txt", "r");
if (!file) {
perror("file open fault");
exit(1);
}
while (fgets(buff, MAXLEN, file)) {
Node *wdNode = (Node *) malloc(sizeof(Node));
wdNode->wd = (char *)malloc(sizeof(char) * strlen(buff));
strcpy(wdNode->wd, buff + 1);
wdNode->wd[strlen(wdNode->wd) - 1] = 0;
fgets(buff, MAXLEN, file);
wdNode->tran = (char *)malloc(sizeof(char) * strlen(buff));
strcpy(wdNode->tran, buff + 6);
wdNode->tran[strlen(wdNode->tran) - 1] = 0;
wdNode->next = head;
head = wdNode;
}
fclose(file);
return head;
}
//用于对单词解释进行切分为多行
void splitWord(const char *trans) {
char *buff = (char *) malloc(sizeof(char *) * (strlen(trans) + 1));
strcpy(buff, trans);
int cnt = 1;
char *token = strtok(buff, "@");
printf("1. %s\n", buff);
while (token = strtok(NULL, "@")) {
printf("%d. %s\n", ++cnt, token);
}
free(buff);
return ;
}
//启动字典进行查询
Node *findNode(Node *head, char *word) {
while (head && strcmp(word, head->wd)) {
head = head->next;
}
return head;
}
void findWord(Node *head) {
char word[MAXLEN];
while (1) {
printf("Please input a word:");
scanf("%s", word);
if (!strcmp(word, "q!")) {
printf("bye~~ ⊙_⊙\n");
break;
}
Node *fd = findNode(head, word);
if (fd) {
printf("%s\n", word);
splitWord(fd->tran);
} else {
printf("%s not find~~>_<~~ \n", word);
}
}
return ;
}
//释放使用的内存,关闭字典
void freeDictionary(Node *head) {
Node *k = head;
while (k) {
head = k->next;
free(k->wd);
free(k->tran);
k = head;
}
free(head);
free(k);
printf("退出字典, T^T\n");
return ;
}
dictionary.c
#include "dictionary.h"
//启动字典进行查询
int main() {
Node *head = loadDictionary();//加载词典
findWord(head);//查询单词
freeDictionary(head); // 释放资源
return 0;
}
运行
虽然简单,但很好的练习了IO的部分知识哦,哈哈哈