客户端查询单词功能
int do_query(int sockfd, MSG *msg)
{
msg->type = Q;
puts("--------------");
while(1)
{
printf("Input word:");
scanf("%s", msg->data);
getchar();
//客户端,输入#号,返回到上一级菜单
if(strncmp(msg->data, "#", 1) == 0)
break;
//将要查询的单词发送给服务器
if(send(sockfd,msg, sizeof(MSG), 0) < 0)
{
printf("Fail to send.\n");
return -1;
}
// 等待接受服务器,传递回来的单词的注释信息
if(recv(sockfd, msg,sizeof(MSG), 0) < 0)
{
printf("Fail to recv.\n");
return -1;
}
printf("%s\n", msg->data);
}
return 0;
}
服务器查询单词功能
int do_searchword(int acceptfd, MSG *msg, char word[])
{
FILE * fp;
int len = 0;
char temp[512] = {};
int result;
char *p;
//打开文件,读取文件,进行比对
if((fp = fopen("dict.txt", "r")) == NULL)
{
perror("fail to fopen.\n");
strcpy(msg->data, "Failed to open dict.txt");
send(acceptfd, msg, sizeof(MSG), 0);
return -1;
}
//打印出,客户端要查询的单词
len = strlen(word);
printf("%s , len = %d\n", word, len);
//读文件,来查询单词
while(fgets(temp, 512, fp) != NULL)
{
// printf("temp:%s\n", temp);
// abandon ab
result = strncmp(temp,word,len);
if(result < 0)
{
continue;
}
if(result > 0 || ((result == 0) && (temp[len]!=' ')))
{
break;
}
// 表示找到了,查询的单词
p = temp + len; // abandon v.akdsf dafsjkj
// printf("found word:%s\n", p);
while(*p == ' ')
{
p++;
}
// 找到了注释,跳跃过所有的空格
strcpy(msg->data, p);
printf("found word:%s\n", msg->data);
// 注释拷贝完毕之后,应该关闭文件
fclose(fp);
return 1;
}
fclose(fp);
return 0;
}
int get_date(char *date)
{
time_t t;
struct tm *tp;
time(&t);
//进行时间格式转换
tp = localtime(&t);
sprintf(date, "%d-%d-%d %d:%d:%d", tp->tm_year + 1900, tp->tm_mon+1, tp->tm_mday,
tp->tm_hour, tp->tm_min , tp->tm_sec);
printf("get date:%s\n", date);
return 0;
}
int do_query(int acceptfd, MSG *msg , sqlite3 *db)
{
char word[64];
int found = 0;
char date[128] = {};
char sql[128] = {};
char *errmsg;
//拿出msg结构体中,要查询的单词
strcpy(word, msg->data);
found = do_searchword(acceptfd, msg, word);
printf("查询一个单词完毕.\n");
// 表示找到了单词,那么此时应该将 用户名,时间,单词,插入到历史记录表中去。
if(found == 1)
{
// 需要获取系统时间
get_date(date);
sprintf(sql, "insert into record values('%s', '%s', '%s')", msg->name, date, word);
if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
{
printf("%s\n", errmsg);
return -1;
}
else
{
printf("Insert record done.\n");
}
}
else //表示没有找到
{
strcpy(msg->data, "Not found!");
}
// 将查询的结果,发送给客户端
send(acceptfd, msg, sizeof(MSG), 0);
return 0;
}
该查询功能中,用到了一个单词表,可以点击dict.txt下载
测试功能

下面进行历史查询模块功能的实现