原编写函数
struct sp
{
int id; //商品编号
char name[20]; //商品名称
char Catagory[10]; //商品类别
int kcl; //商品库存量
int xsl; //商品销售量
struct sp*next; //指向下一节点
};
void shanchu(sp *L)
{
char n[20];
sp *p=L->next,*head=L;
if(p==NULL)
printf("无法删除!");
else
{
printf("请输入要删除的商品名称:");
scanf("%s",n);
while(strcmp(p->name,n)!=0)
{
head=p;
p=head->next;
if(p=NULL)
{
printf("没有找到相关信息,无法删除\n");
return;
}
}
head->next=p->next;
free(p);
printf("删除成功");
}
}
要在此函数上添加文件
我的思路是在先打开文件,把文件中数据读到系统内存,然后查询删除,最后再把剩下的数据写入到原文件中。
加入文件后(数据格式为:棉花糖 食品 20001 60 400 棒棒糖 食品 20002 50 32 ...)
void shanchu(sp *L)
{
FILE *fp;struct sp*p,*head;
if((fp=fopen("sp.txt","r+"))==NULL)
{
printf("不能打开文件!\n");
exit(0);
}
while(1) //文件读入到系统内存
{
p=(struct sp *)malloc(sizeof(struct sp));
p->next=NULL;
if(fscanf(fp,"%s %d %s %d %d ",p->name,&p->id,p->Catagory,&p->kcl,&p->xsl)!=5)
break;
p->next=L->next;
L->next=p;
}
free(p);
fclose(fp);
char n[20]; //开始查找删除
p->next=L->next,head=L;
if(p==NULL)
printf("无法删除!");
else
{
printf("请输入要删除的商品名称:");
scanf("%s",n);
while(strcmp(p->name,n)!=0)
{
head=p;
p=head->next;
if(p=NULL)
{
printf("没有找到相关信息,无法删除\n");
return;
}
}
head->next=p->next;
free(p);
while(1) //把剩下的数据重新写入到原文件
{
p->next=NULL;
p=(struct sp *)malloc(sizeof(struct sp));
FILE *fp;
fp=fopen("sp.txt","a");
fprintf(fp,"%s %d %s %d %d ",p->name,p->id,p->Catagory,p->kcl,p->xsl);
p->next=L->next;
L->next=p;
if(p==NULL)break;
}
free(p);
fclose(fp);
printf("删除成功");
}
}
加上后有错误,各位大佬帮我看下,帮我改下代码,谢谢!!