Linux:实现字典查询功能

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);

}

结果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值