结构体(采用动态链表)的储存读取,以及fread函数的使用。

如下问题描述的比较清晰,不会难懂的,大神们帮帮忙!! 如果有其他好的方法也求赐教。
定义了一个结构体类型如下
struct Student /*建立结构体类型*/
{
char num[12];
char name[10];
char clas[20];
char sex[4];
char birth[20];
struct Student *next; //存放结构体指针
};

假设这个链表有n>1个结点,表头为pHead,然后我用fwrite函数写到文件中保存,如下:

void Save_To_File(Student* pHead) //(给定表头pHead作为参数)
{
FILE* fp;
fp = fopen("stud.dat", "wb");
Student* p = pHead;
while (p)
{
fwrite(p, sizeof(struct Student),1, fp);
p = p->next;
}
printf("所有信息已存储至文件Stud.bat");
fclose(fp);
}

假设我现在保存了文件。然后关闭程序,再打开程序。

如果我想用fread函数把我的结构体数据读出来,应该怎么做?fread(buffer,size,count,fp)的buffer是数据存放的地址,但是我怎么得知这个地址? 我看到书上一些结构体已经定义好元素数量,可以直接通过那个&stud[i]来作为buffer(如下面的代码),但是我的结构体运用动态链表,是没有固定的元素个数的,也没有这个结构变量名,也就是说没办法通过结构变量名来作为buffer,何解?
struct Student /*建立结构体类型*/
{
char num[12];
}stud[20];
........
fread(&stud[i],xxx,xxx,xxx)
........

问题大概就这样子了。

完整测试代码如下,思路就是从文件读出的时候重建链表。

#include "stdio.h"
#include "malloc.h"
#include "string.h"
 
struct Student       /*建立结构体类型*/
{
 char num[12]; 
 char name[10]; 
 char clas[20]; 
 char sex[4]; 
 char birth[20]; 
 struct Student *next;     //存放结构体指针
};
 
void Save_To_File(Student *pHead);  //(给定表头pHead作为参数)
void Read_From_File(Student *pHead);     //(给定表头pHead作为参数) 
 
void main()
{
 int a;
 Student *pHead, *p, *pNext;
 
 // 表头
 pHead = (Student *)malloc(sizeof(Student));
 strcpy(pHead->birth, "1");
 strcpy(pHead->clas, "1");
 strcpy(pHead->sex, "1");
 strcpy(pHead->num, "1");
 strcpy(pHead->name, "1");
 
 p = (Student *)malloc(sizeof(Student)); // 第2个节点
 pHead->next = p;
 strcpy(p->birth, "2");
 strcpy(p->clas, "2");
 strcpy(p->sex, "2");
 strcpy(p->num, "2");
 strcpy(p->name, "2");
 
 pNext = (Student *)malloc(sizeof(Student)); // 第3个节点
 p->next = pNext;
 p = pNext;
 strcpy(p->birth, "3");
 strcpy(p->clas, "3");
 strcpy(p->sex, "3");
 strcpy(p->num, "3");
 strcpy(p->name, "3");
 p->next = NULL;  // 终结链表
 
 Save_To_File(pHead);
 
 free(pHead); // 为测试,仅释放 pHead,其他节点暂时不管了
 
 pHead = (Student *)malloc(sizeof(Student));
 Read_From_File(pHead);
 
 // 输出看是否正确读出
 p = pHead;
 while (p)
 {
  printf("Num=%s, Name=%s, Clas=%s, Sex=%s, Birth=%s\n", p->num, p->name, p->clas, p->sex, p->birth);
  p = p->next;
 }
}

void Save_To_File(Student *pHead)     //(给定表头pHead作为参数) 
{  
 FILE* fp;  
 fp = fopen("stud.dat", "wb");  
 Student* p = pHead;  
 while (p)  
 {   
  fwrite(p, sizeof(Student),1, fp); // 这里不应该用sizeof(struct Student),意思不一样
  p = p->next; 
 }  
 printf("所有信息已存储至文件Stud.dat。\n"); 
 fclose(fp); 
}
 
void Read_From_File(Student *pHead)     //(给定表头pHead作为参数) 
{
 FILE* fp;
 Student *p, *pNext;
 fp = fopen("stud.dat", "r");
 p = pHead;
 while (fread(p, sizeof(Student), 1, fp))
 {
  if (p->next != NULL) // 如果读出的不是最后一个结点,为下一个节点分配空间并处理
  {
   pNext = (Student *)malloc(sizeof(Student));
   p->next = pNext;
   p = pNext;
  }
 }
 printf("所有信息已读出到链表。\n");
 fclose(fp);

追问

好像真的可以!!! 点一个赞 fread(buffer,xx,xx,xx) 这里的buffer是指把数据读出来的后存放的地点吗?我一直以为这个buffer是数据在文件中的地址

追答

buffer是内存里的地址,不是文件。文件读写的位置由文件位置指针确定,这个指针在读写文件时会自动移动

温馨提示:答案为网友推荐,仅供参考
相似回答