Day14.快译通
main.c
#include "fun.h"
int main(void)
{
DICT* p = (DICT*)malloc(sizeof(DICT) * WORDMAX);
file_read(p);
while (1)
{
word_inquiry(p);
int flag = 0;
flag = word_inquiry(p);
if (flag != 1)
{
printf("没有找到该单词!\n");
}
}
free_room(p);
return 0;
}
fun.h
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define WORDMAX 3
struct word_dict
{
char* word;
char* trans;
};
typedef struct word_dict DICT;
void file_read(DICT* p);
int word_inquiry(DICT* p);
void free_room(DICT* p);
fun.c
#include "fun.h"
//打开文件读取文件
void file_read(DICT* p)
{
FILE* fp = fopen("dict.txt", "r");
if (!fp)
return -1;
int i = 0;
char buf[1024];
while (!feof(fp))
{
//创建堆空间,读取文件
memset(buf, 0, 1024);
fgets(buf, 1024, fp);
p[i].word = (char*)malloc(strlen(buf) + 1);
memset(p[i].word, 0, strlen(buf) + 1);
strcpy(p[i].word, buf + 1);
memset(buf, 0, 1024);
fgets(buf, 1024, fp);
p[i].trans = (char*)malloc(strlen(buf) + 1);
memset(p[i].trans, 0, strlen(buf) + 1);
strcpy(p[i].trans, buf);
i++;
}
fclose(fp);
}
//获取单词,查询
int word_inquiry(DICT* p)
{
char buf[1024];
memset(buf, 0, 1024);
fgets(buf, 1024, stdin);
if (!strncmp("comm=exit", buf, 9))
{
exit(0);
}
for (int i = 0; i < WORDMAX; i++)
{
if (strcmp(p[i].word, buf) == 0)
{
printf("%s", p[i].trans);
return 1;
}
}
return 0;
}
void free_room(DICT* p)
{
for (int i = 0; i < WORDMAX; i++)
{
free(p[i].word);
free(p[i].trans);
}
free(p);
}
dict.txt
#a
translate:art. 一(个);每一(个);任一(个)
#take
translate:v. 拿;取;携带;夺取;吃,喝;写下;拍照;接收;
#hello world
translate:你好 世界