读写文件

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct stu//结构体
{
char num[20];
char name[20];
struct stu * next;
}pstu,*st;
void write(pstu *head)//写入文件,写入文件不用返回值,只是让这个函数执行写入文件的过程,需要吧链表传进去
{
if(head==NULL || head->next==NULL)//判断链表是否为空
{
printf("error");
return ;
}
FILE * fp;//文件指针
fp=fopen("456.txt","a+");//打开文件  有时候单用w方式写入文件,会出现覆盖写的问题,,,所以用上了a+方式
if(fp==NULL)
{
printf("error");
return ;
}
printf("打开的文件\n");
int ret;
// st temp=head->next;
// while(head->next!=NULL)//保存进文件,知道链表全部遍历完
{//因为是只有一个结构体存入,所以没有用循环
ret=fwrite(head->next,sizeof(pstu),1,fp);//存
if(ret<0)
{
printf("error");
return ;
}
// head=head->next;
}
fclose(fp);//关闭文件
}
st read()//读文件
{
st head=(st)malloc(sizeof(pstu));//定义头节点
head->next=NULL;
st temp=(st)malloc(sizeof(pstu));       //
FILE *fp;
fp=fopen("456.txt","r");
if(fp==NULL)
{
printf("file empty\n");
return NULL;
}
while(fread(temp,sizeof(pstu),1,fp)>0)//把文件中的东西保存进以head为头节点的链表中
{
// head->next=temp->next;//问题出在这,导致一直读取文件失败
temp->next=head->next;//首先head->next里面是置空的
head->next=temp;
temp=NULL;
temp=(st)malloc(sizeof(pstu));
}
free(temp);


temp=NULL;
fclose(fp);
return head;//返回整个链表
}
void add()//为文件添加数据
{
// st head=(st)malloc(sizeof(pstu));定义的时候,需要置空,而不是分配空间
st head=NULL;
head=read();//首先读取文件,以链表形式赋值给head
if(head==NULL)
{
head=(st)malloc(sizeof(pstu));
head->next=NULL;
}
head->next=NULL;
st p=(st)malloc(sizeof(pstu));
printf("输入号码:");
scanf("%s",p->num);
printf("输入姓名:");
scanf("%s",p->name);
// head->next=p->next;    与上面同样的问题
p->next=head->next;
head->next=p;
write(head);


}

void show()//显示函数
{
st head=read();
if(head==NULL || head->next==NULL)
{
printf("the link is empty\n");
return;
}
while(head->next!=NULL)
{
printf("%s\t%s\n",head->next->num,head->next->name);
head=head->next;
}
}
int main()
{
// add();
show();

}


//刚开始出现问题,是显示不出来的问题,所以就在show()函数里面找问题,一直改,最后发现在读文件里面与写文件时犯同样的错-----无值赋有值(head->next=p->next; )

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值