VS2013下测试通过
主要涉及的知识有:1、指针(一级,二级)
2、内存管理(malloc(),free().memset(),stecpy())
3、文件读取(fopen,fclose)
目前还有一点问题:在匹配的时候会根据输入的长度匹配(strncmp()的原因),这样导致会匹配到第一个包含输入的文件行内容,导致不准确。如:会 ->会餐 ->dinner。解决方法:
1、文件里面完善,添加新的词条语义,且保证短词在长词前面出现
2、程序里面完善,再用文件词条长度比较一次(strncmp())
两种方式似乎都不太好,对于第一种,要添加的词条语义数很多,对于第二种,可能会漏掉某些短词(鼾==鼾声),要解决漏掉又要用第一种方式。
/* *wffos 20170324 */ #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include <string.h> #define MAX 111111 //词条语义对 struct Dict { char *key; char *content; }; //功能:打开文件,将词条语义对保存在内存中 //入参:内存地址,文件名 int openDict(struct Dict **p, const char *pFileName) { FILE *pFile = fopen(pFileName, "r");//打开文件 if (pFile == NULL) return 0;//打开文件失败 *p = (struct Dict *)malloc(sizeof(struct Dict)*MAX); memset(*p, 0, sizeof(struct Dict)*MAX);//初始化为0 char tempBuf[1024] = { 0 };//用来临时存储每一行数据 int len = 0;//保存临时数据长度 int i = 0;//词条语义对计数 while (!feof(pFile)) { //读第一行 memset(tempBuf, 0, sizeof(tempBuf)); fgets(tempBuf, sizeof(tempBuf), pFile); len = strlen(tempBuf); if (len > 0) { (*p)[i].key = (char *)malloc(sizeof(char *)*len); memset((*p)[i].key, 0, len); strcpy((*p)[i].key, &tempBuf[1]);//读取开始位置跟文件结构相关 } //读第二行 memset(tempBuf, 0, sizeof(tempBuf)); fgets(tempBuf, sizeof(tempBuf), pFile); len = strlen(tempBuf); if (len > 0) { (*p)[i].content = (char *)malloc(sizeof(char *)*len); memset((*p)[i].content, 0, len); strcpy((*p)[i].content, &tempBuf[6]);//读取开始位置跟文件结构相关 } ++i;//读完两行,计数 } fclose(pFile);//关闭文件 return i; } //功能:根据词条查找对应语义 //入参:保存有词条语义对的内存,保存有词条语义对的内存大小,词条,语义) int serchDict(struct Dict *p, int pSize, char *key, char *content) { int i = 0; for (i; i < pSize; i++) { if ((p[i].key == NULL) || (p[i].content == NULL))//这个不能少,没找到的情况 continue; if (strncmp(p[i].key, key, strlen(key)) == 0) { memcpy(content, p[i].content, strlen(p[i].content)); return 1;//找到返回1(千万别返回i,第一条会找不到) } } return 0; } //功能:释放内存 //入参:保存有词条语义对的内存,保存有词条语义对的内存大小 void freeDict(struct Dict *pD, int pSize) { int i = 0; for (i; i < pSize; i++)//释放词条语义 { if (pD[i].key) free(pD[i].key); if (pD[i].content) free(pD[i].content); } free(pD);//释放保存有词条语义对的内存 } int main() { struct Dict *pD = NULL; int pSize = openDict(&pD, "E:/学习/VS 2013/wffosDictionary/Debug/dict.txt");//第二个参数做文件地址 if (pSize == 0) return 0;//打开字典文件失败,程序退出 char key[1024] = { 0 }; char content[1024] = { 0 }; while (1) { memset(key, 0, sizeof(key)); memset(content, 0, sizeof(content)); scanf("%s", key); if (strncmp(key, "command=exit", 12) == 0) break; if (serchDict(pD, pSize, key, content)) printf("%s", content); else printf("Not Found\n"); } freeDict(pD, pSize); return 0; }