可存在文件中的通讯录
通过file函数对文件进行操作,使其能够下次打开时不至于丢失。
通过Loadcontact函数对文件contact进行操作 读取其中的数据,并且判断是否要进行扩容
void LoadContact(struct Contact* pc)
{
//打开文件
FILE *pfin = fopen("contact.dat","rb");
if (pfin == NULL)
{
printf("LoadContact %s\n", strerror(errno));
return;
}
//读取文件内容
struct PerInfo tmp = { 0 };
while( (fread(&tmp, sizeof(struct PerInfo), 1, pfin)) != 0)
{
//检测是否增容
if (Check_Capacity(pc) == 0)
{
printf("通讯录增容失败\n");
return;
}
//存储元素
pc->data[pc->sz] = tmp;
pc->sz++;
}
fread(&tmp,sizeof(struct PerInfo),1,pfin);
//关闭文件
fclose(pfin);
pfin = NULL;
}
文件存属于该工程的目录中
最后将写在内存中的数据存到文件中
void SaveContact(struct Contact* pc)
{
FILE *pfout = fopen("contact.dat", "wb");
if (pfout == NULL)
{
printf("SaveContact%s\n", strerror(errno));
return ;
}
//写数据
int i = 0;
for (i = 0; i < pc->sz; i++)
{
fwrite(pc->data + i, sizeof(struct PerInfo), 1, pfout);
}
//关闭文件
fclose(pfout);
pfout = NULL;
printf("保存成功\n");
}
由于完整代码和博主的中阶代码相似无法上传,需要者可以直接去我的网盘
网盘链接
密码 9696
有什么问题可以直接私信博主,大家一起学习一起进步!