嵌入式编程——数据结构与linux编程
根据dict.txt文件中的内容,用户输入单词获得单词含义
#include "public.h"
int main(void)
{
struct list_head *parray = NULL;
FILE *fp = NULL;
char *nret = NULL;
char *pword = NULL;
char *pparaphrase = NULL;
int num = 0;
char str[1024] = {0};
char word[256] = {0};
fp = fopen("./dict.txt", "r");
if(fp == NULL)
{
ERR_MSG("打开失败\n");
return -1;
}
parray = create_hashtable();
while(1)
{
nret = fgets(str, sizeof(str), fp);
{
if(nret == NULL)
{
break;
}
}
pword = str;
pparaphrase = str;
while(1)//定位单词
{
if(*pparaphrase == ' ')
{
*pparaphrase = '\0';
break;
}
pparaphrase++;
}
while(1)//定位释义
{
pparaphrase++;
if(*pparaphrase != ' ')
{
break;
}
}
insert_hashtable(parray, pword, pparaphrase);
}
//show_hashtable(parray);
while(1)
{
printf("输入1查询单词 任意键数字退出\n");
scanf("%d", &num);
getchar();
if(num == 1)
{
printf("请输入要查询的单词\n");
gets(word);
if(find_hashtable(parray, word) != NULL)
{
printf("%s \n", find_hashtable(parray, word)->paraphrase);
}
else
{
printf("未找到\n");
}
}
else
{
break;
}
}
destroy_hashtable(parray);
parray = NULL;
fclose(fp);
return 0;
}
#ifndef __PUBLIC_H__
#define __PUBLIC_H__
#include "list.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include <errno.h>
#include <error.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <time.h>
//结构体
typedef struct hashnode
{
struct list_head node;
char word[128];
char paraphrase[1024];
}hashnode_t;
//打印出错信息
#define ERR_MSG(message) do { \
printf("[%s%7d]%s:%s\n", __FILE__, __LINE__, message, strerror(errno)); \
}while (0)
//更新开始计时时间
#define GET_START_TIME do { \
gettimeofday(&starttime, NULL); \
} while (0)
//更新结束计时时间
#define GET_END_TIME do { \
gettimeofday(&endtime, NULL); \
} while (0)
//获得耗时时间
#define GET_CONST_TIME (((endtime.tv_sec * 1000000 + endtime.tv_usec) - (starttime.tv_sec * 1000000 + starttime.tv_usec)) / 1000.0)
//哈希结构体参数
#define MAXNUM 52
//声明
extern struct list_head *create_hashtable(void);
extern int insert_hashtable(struct list_head *pheadlist, char *pstr, char *pstd);
extern int show_hashtable(struct list_head *pheadlist);
extern hashnode_t *find_hashtable(struct list_head *pheadlist, char *pstr);
extern int delete_hashtable(struct list_head *parray, char *pstr);
extern int destroy_hashtable(struct list_head *parray);
struct timeval starttime;
struct timeval endtime;
#endif