//main.c
#include
#include
#include "list.h"
int main()
{
struct Word *head;
head=creatLink();
listToFile(head);
return 0;
}
//list.h
#ifndef _LIST_H
#define _LIST_H
struct Word
{
char japanese[20];//日文
char kana[20];//假名
int accent;//声调
char property[10];//词性
char chinese[30];//中文
struct Sentense *head2;//句子结构体链表的头指针
struct Word *next;//下一个结点地址
};
struct Sentense
{
char sentense[50];//例句
struct Sentense *next;//下一个结点地址
};
FILE *inputOneWord_F(struct Word *p,FILE *fp);
struct Word *creatLink();
FILE *outputOneWord_F(struct Word *t,FILE *fp);
void listToFile(struct Word *head);
#endif // _LIST_H
//list.c
#include
#include
#include "list.h"
#define LEN sizeof(struct Word)
#define LEN2 sizeof(struct Sentense)
//将文件中一个Word结构体中的所有数据读入p所指向的链表结点,返回值为指针目前在文件中所在的位置
FILE *inputOneWord_F(struct Word *p,FILE *fp)
{
char a;
fscanf(fp,"%s%s%d%s%s",p->japanese,p->kana,&p->accent,p->property,p->chinese);
struct Sentense *g,*tail=NULL; //新建Sentense结构体单链表
p->head2=NULL;
while(1){
fgetc(fp);//吸收换行符
a=fgetc(fp);//通过是否为换行符来判断当前单词有无例句
if(a=='\n'||feof(fp)) break; //说明此单词无例句返回指针目前在文件中所在的位置,进行下一个单词的读取
else{
fseek(fp,-1l,SEEK_CUR);//光标向前一个字符
fputc(a,fp);//将刚才从文件读取的字符按原样写入文件(位置不变)
g=(struct Sentense*)malloc(LEN2);//
fscanf(fp,"%s",g->sentense);
if(p->head2==NULL)p->head2=g;//如果链表为空,新建立的结点就是链表的头结点
else tail->next=g;
tail=g;//tail永远指向链表的尾结点
}
}
tail->next=NULL;
return fp;
}
//在程序执行之初将上一次存储在文件中的全部数据读入新建Word结构体单链表,函数返回单链表头指针
struct Word creatLink()
{
struct Word *p,*head=NULL,*rear=NULL;
FILE *fp;
fp=fopen("WordList.txt","r");
if(fp==NULL)
{
printf("单词表为空!");
return head;
}
p=(struct Word)malloc(LEN);
fp=inputOneWord_F(p,fp);//更改指针在文件中所在的位置
while(!feof(fp))
{
if(head==NULL)head=p;
else rear->next=p;
rear=p;
p=(struct Word*)malloc(LEN);
fp=inputOneWord_F(p,fp);
}
rear->next=p;
rear=p;
rear->next=NULL;
fclose(fp);
return head;
}
FILE *outputOneWord_F(struct Word *t,FILE *fp)
{
fprintf(fp,"\n%s %s %d %s %s\n",t->japanese,t->kana,t->accent,t->property,t->chinese);
struct Sentense *p;
p=t->head2; //p为指向Word结构体中Sentense结构体链表的头指针;
while(p!=NULL)
{
fprintf(fp,"%s\n",p->sentense);
p=p->next;
}
return fp;
}
//程序运行结束之际将链表中的数据全部写入文件
void listToFile(struct Word *head)
{
FILE *fp;
fp=fopen("WordList2.txt","w");
struct Word *p;
p=head;
while(p!=NULL)
{
fp=outputOneWord_F(p,fp);
p=p->next;
}
fclose(fp);
}