链表写入文件时为什么不行?

来源:百度知道 编辑:UC知道 时间:2024/05/31 02:48:52
//函数功能:文件写入,读出链表
#include "stdio.h"
#include "malloc.h"
#define NULL 0
#define size 5
#define TYPE struct file
#define LEN sizeof(struct file)
//定义结格体file
struct file
{
char name[10];
char data[10];
char status[2]; //file结构体参数变量
struct file *next; //file 指针指向下一个地址
}file[size]; //file数组
//函数名称:write
//函数功能:写文件进链表
//返回值:返回值为空
//head是头指针;p为文件指针
struct file *write(void)
{
struct file *head;
FILE *fp;
if((fp=fopen("file_name","wb"))==NULL) //打开文件名为:file_name的文件
{
printf("can not open the file!\n");
return(NULL);
}
while (head!=NULL) //判断头指针是否为空
{
head=(TYPE*)malloc(LEN); //为头指针自动分配内存空间
fwrite(head,LEN,1,fp); //数据写入文件
head=head->next; //指向下一地址
}
head->next=NULL;
return(NULL);<

//函数功能:文件写入,读出链表
#include "stdio.h"
#include "malloc.h"
#define size 5
#define TYPE struct file
#define LEN sizeof(struct file)
//定义结格体file
struct file
{
char name[10];
char data[10];
char status[2]; //file结构体参数变量
struct file *next; //file 指针指向下一个地址
}file[size]; //file数组
//函数名称:write
//函数功能:写文件进链表
//返回值:返回值为空
//head是头指针;p为文件指针
struct file *write(void)
{

FILE *fp;
int i=0;

if((fp=fopen("file_name.txt","wb"))==NULL) //打开文件名为:file_name的文件
{
printf("can not open the file!\n");

}

for(i=0;i<size;i++)
fwrite(&file[i],LEN,1,fp); //数据写入文件

fclose(fp);
return(NULL);
}

//函数名称:read
//函数功能:从链表中读出文件
//返回值:返回值为空
//head,p1,p2为定义的链表指针,fp为文件指针
struct file *read(void)
{
struct file *head;//,*p