这段程序不知道什么用,有人可以看看吗

int n;
if ((fp = fopen("student.txt", "a")) == NULL)
{
printf("File open error!\n");
exit(1);
}
fclose(fp);
if ((fp = fopen("student.txt", "r")) == NULL)
{
printf("File open error!\n");
exit(1);
}
p1 = (struct student*)malloc(sizeof(struct student));
p1->next = NULL;
head = p1;
while (!feof(fp))
{
if (fread(p1, sizeof(struct student), 1, fp) != 1)
break;
p2 = (struct student*)malloc(sizeof(struct student));
p2->next = NULL;
p1->next = p2;
p1 = p2;
}
}

首先判断student.txt是否可读可写,然后将txt文件中按照结构体student的内容分别读出并保存在指针p1内存上。

  1. 前两次fopen的目的,应该是看看student.txt文件的权限是否具备可读可写,并且万一没有该文件,也会创建一个student.txt文件,内容是空的
  2. 之后创建了一个单链表,表头为head
  3. 只要student.txt文件没读到末尾,就把每次读取到的1*sizeof(struct student)个字节的数据,放到刚刚新建出来的指针空间p2内,并且重复用p2覆盖p1的内存空间中的数据

这段代码有两个可能存在的问题,让它看起来根本没有意义:

  1. p2不断覆盖p1的数据,这条单链表只有两个有效成员
  2. fread判断的字节为 != 1,我不知道1*sizeof(struct student)是不是一定==1,如果不是,那程序直接就break,没有任何有意义的赋值执行

用来读取文件student.txt,将结果放到结构体中