Linux:实现字典查询功能
字典文件word.txt
#a
#trans:a is a letter
#b
#trans:b is a letter also
#hello
#trans:you can say helloworld
代码:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
typedef struct test_word_transfer
{
char * word;
char * trans;
}sword;
int main(void * argc, void * argv)
{
FILE * fp = fopen("/home/michael/test_word_transfer/word.txt","r");
if(!fp)
{
printf("open file fail\n");
return -1;
}
sword * list = (sword *)malloc(sizeof(sword)*3);
char * temp = (char *)malloc(sizeof(char)*1024);
int i=0;
while (!feof(fp))
{
memset(temp,0,1024);
fgets(temp,1024,fp);
// printf("%s",temp);
temp[strlen(temp)-1] = 0; //去除尾部\n
list[i].word = (char*)malloc(sizeof(char)*strlen(temp));
strcpy(list[i].word,temp+1);
// printf("%s",list[i].word);
memset(temp,0,1024);
fgets(temp,1024,fp);
// printf("%s",temp);
temp[strlen(temp)-1] = 0;//去除尾部\n
list[i].trans = (char*)malloc(sizeof(char)*strlen(temp));
strcpy(list[i].trans,temp+7);
// printf("%s",list[i].trans);
i++;
}
char * word = (char *)malloc(sizeof(char)*1024);
char * trans = (char *)malloc(sizeof(char)*1024);
while (1)
{
memset(word,0,1024);
memset(trans,0,1024);
_Bool t = 0;
scanf("%s",word);
if(!strcmp("exit",word)) break;
for(int i = 0; i< 3; i++) {
if(!strcmp(word,list[i].word))
{
printf("%s\n",list[i].trans);
t = 1;
continue;
}
}
if(t) {
continue;
}
else{
printf("not find! %s\n",word);
}
}
// for(int i=0; i < 3; i++)
// {
// list[i].word = (char *)malloc(sizeof(char)*100);
// list[i].trans = (char *)malloc(sizeof(char)*100);
// fgets(list[i].word,100,fp);
// fgets(list[i].trans,100,fp);
// }
// for (i = 0; i < 3; i++)
// {
// printf("%s\n",list[i].word);
// printf("%s\n",list[i].trans);
// }
for(i = 0; i<3 ; i++){
free(list[i].word);
free(list[i].trans);
}
free(list);
free(word);
free(trans);
}