C语言用指针和链表读写文件_c语言链表的文件读写
C语言用指针和链表读写文件由刀豆文库小编整理,希望给你工作、学习、生活带来方便,猜你可能喜欢“c语言链表的文件读写”。
#include
#include
#include
#include
#define MAXLEN_OF_KEYWORD 50
#define MAXLEN_OF_KEYWORDTYPE 30
char i,ch[5];
struct KeyWordBox
{
char Name[MAXLEN_OF_KEYWORD];
intId;
char Type[MAXLEN_OF_KEYWORDTYPE];//该单词的类型struct KeyWordBox *next;//指针
};
void write();
void read();
void main()
{
write();
read();
}
void write()
{
char *FileName=“FileName.txt”;
KeyWordBox transport;
memset(&transport,0,sizeof(struct KeyWordBox));
FILE *out=NULL;
FILE *test=NULL;
test=fopen(FileName,“a”);
if(test==NULL)
{
out=fopen(FileName,“w”);
printf(“ 1 continue,0 exitn”);
i=getchar();
while(i=='1')
{
printf(“请输入关键字n”);
scanf(“%s”,transport.Name);
printf(“请输入IDn”);
scanf(“%d”,&transport.Id);
printf(“请输入Typen”);
scanf(“%s”,transport.Type);
fwrite(&transport,sizeof(struct KeyWordBox),1,out);
printf(“ 1 continue,0 exitn”);
scanf(“%c”,&i);
}
fclose(out);
}
else
{
out=fopen(FileName,“a”);
printf(“ 1 continue,0 exitn”);
scanf(“%c”,&ch);
//i=getchar();
//while(i=='1')
while(strcmp(ch,“1”)==0)
{
printf(“请输入关键字n”);
scanf(“%s”,transport.Name);
printf(“请输入IDn”);
scanf(“%d”,&transport.Id);
printf(“请输入Typen”);
scanf(“%s”,transport.Type);
fwrite(&transport,sizeof(KeyWordBox),1,out);
printf(“ 1 continue,0 exit.n”);
scanf(“%s”,ch);
}
fclose(out);
}
}
void read()
{
char *FileName=“FileName.txt”;
KeyWordBox *Head=NULL,*q=NULL;
KeyWordBox *Body=NULL;
KeyWordBox *p=NULL;
FILE *in=NULL;
in=fopen(FileName,“r”);
if(in==NULL)
{
printf(“can't open the file!n”);
exit(0);
}
else
{
Head=(struct KeyWordBox*)malloc(sizeof(struct KeyWordBox));Head->next =NULL;
}}q=Head;while(!feof(in)){Body=(struct KeyWordBox*)malloc(sizeof(struct KeyWordBox));Body->next=NULL;fread(Body,sizeof(struct KeyWordBox),1,in);if(feof(in)){q->next=NULL;break;}q->next=Body;q=Body;printf(“%st%dt%sn”,Body->Name,Body->Id,Body->Type);} fclose(in);p=Head->next;while(p!=NULL){printf(“%st%dt%sn”,p->Name,p->Id,p->Type);p=p->next;}