//这里用集合的例子
//集合的结构体:
typedef struct Aggreage//集合
{
DataType element;//元素
struct Aggreage *next;
}SAggreage;
//读文件数据到链表
void load(SAggreage* ha,SAggreage* hb)
{
SAggreage* p = NULL;
FILE *fp = NULL;
//将数据读到集合A
if((fp = fopen("A.txt","r")) == NULL)
{
cout<<"打开文件失败!"<<endl;
}
else
{
while(!feof(fp))
{
if ((p = (SAggreage*)malloc(sizeof(SAggreage))) == NULL)
{
printf("\n --无法分配内存空间!\n");
fclose(fp);
}
fscanf(fp,"%c ",&p->element);
p->next = ha->next;
ha->next = p;
}
fclose(fp);
}
//将数据读到集合B
if((fp = fopen("B.txt","r")) == NULL)
{
cout<<"打开文件失败!"<<endl;
}
else
{
while(!feof(fp))
{
if ((p = (SAggreage*)malloc(sizeof(SAggreage))) == NULL)//创建一个结构体长度的空间
{
printf("\n --无法分配内存空间!\n");
fclose(fp);//打开错误或者结束读写是记得关了文件,特别是打开错误的时候
}
//可以分配空间
fscanf(fp,"%c ",&p->element);
p->next = hb->next;
hb->next = p;
}
fclose(fp);
}
}
fscanf(读文件的数据到结构体)的用法:
fscanf(fp, "%d %s %c %d %lf", &emp[i].eid, emp[i].name, &emp[i].gender, &emp[i].age, &emp[i].score);
fprintf(读结构体的数据到文件)的用法:
fprintf(fp, "%d %s %c %d %lf", emp[i].eid, emp[i].name, emp[i].gender, emp[i].age, emp[i].score);