成语大全网 - 汉语词典 - c词典用法插入

c词典用法插入

/*基本的库函数*/

#include <conio.h>

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define szWORD 32

#define szSTRN 224

#define szITEM sizeof(struct TItem)

char fileDict[szSTRN];

typedef struct TItem {

char word[szWORD];

char mean[szSTRN];

} Item;

fpos_t lookup(char *word, char *mean)

{

FILE * f = 0; Item i;

int r = 0; fpos_t p = 0;

if(!word) return 0;

f = fopen(fileDict, "rb");

if (!f) return 0;

while(!feof(f)) {

fgetpos(f, &p);

r = fread(&i, szITEM, 1, f);

if(r < 1) break;

if(i.word[0] == 0) continue;

if(strcmp(i.word , word)) continue;

if(mean) strcpy(mean, i.mean );

fclose(f);

return p+1;

}

fclose(f);

return 0;

}

void append(void)

{

Item i; FILE * f = 0; fpos_t p = 0;

memset(&i, 0, szITEM);

printf("请输入单词:"); scanf("%s", i.word );

p = lookup(i.word, 0 );

if(p) {

printf("字典内已经有该单词记录!\n");

return;

}

printf("请输入释义,按回车结束:");

fflush(stdin);

gets(i.mean );

f = fopen(fileDict, "ab");

fwrite(&i, szITEM, 1, f);

fclose(f);

printf("词条已新增\n");

}

void erase(void)

{

Item i; FILE * f = 0; fpos_t p = 0;

memset(&i, 0, szITEM);

printf("请输入单词:"); scanf("%s", i.word );

p = lookup(i.word, 0 );

if(p==0) {

printf("字典内没有该单词记录!\n");

return;

}

p--;

memset(&i, 0, szITEM);

f = fopen(fileDict, "rb+");

fsetpos(f, &p);

fwrite(&i, szITEM, 1, f);

fclose(f);

printf("词条已删除\n");

}

void edit(void)

{

Item i; FILE * f = 0; fpos_t p = 0;

memset(&i, 0, szITEM);

printf("请输入单词:"); scanf("%s", i.word );

p = lookup(i.word, 0 );

if(p==0) {

printf("字典内没有该单词记录!\n");

return;

}

p--;

printf("请输入释义,按回车结束(输入abort放弃修改):");

fflush(stdin);

gets(i.mean );

if(strstr(i.mean ,"abort")) {

printf("已放弃修改!\n");

return ;

}

f = fopen(fileDict, "rb+");

fsetpos(f, &p);

fwrite(&i, szITEM, 1, f);

fclose(f);

printf("词条已保存\n");

}

void query(void)

{

Item i; fpos_t p = 0;

memset(&i, 0, szITEM);

printf("请输入单词:"); scanf("%s", i.word );

p = lookup(i.word, i.mean );

if(p==0) {

printf("字典内没有该单词记录!\n");

return;

}

printf("词条%s\n释义%s", i.word , i.mean );

}

void set(void)

{

int cmd = 0;

printf("当前字典为%s,需要改变吗(选择y或Y改变)?", fileDict);

cmd = getch();

if(cmd == 'y' || cmd == 'Y') {

printf("请输入字典文件名称(包含路径):");

scanf("%s", fileDict);

printf("设置成功!\n");

}

}

int main(int argc, char * argv[])

{

int cmd = 0;

if(argc >1)

strcpy(fileDict, argv[1]);

else

strcpy(fileDict, "c:\\dict.txt");

/*end if*/

for(;;) {

printf("\n\

************************\n\

** 欢迎使用迷你字典!**\n\

************************\n\

** 0 - 设置字典 **\n\

** 1 - 查询词条 **\n\

** 2 - 新增词条 **\n\

** 3 - 编辑词条 **\n\

** 4 - 删除词条 **\n\

** 5 - 退出字典 **\n\

************************\n");

cmd = getch() - '0';

switch(cmd) {

case 0: set(); break;

case 1: query(); break;

case 2: append(); break;

case 3: edit(); break;

case 4: erase(); break;

default: return 0;

}

}

return 0;

}