c语言 链表 指针 文件

来源:百度知道 编辑:UC知道 时间:2024/05/12 00:51:59
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "alloc.h"
typedef struct student
{char num[8];
char name[10];
float Chinese;
float English;
float Math;
struct student *next;
}ST,*STU;

STU crelink(int n)
{int i;
STU head,p,q;
FILE *fp;
if(n<=0) return NULL;
head=(STU)malloc(sizeof(ST));
printf("Input date:\n");
if((fp=fopen("STUDENT.TXT","a"))==NULL)
{printf("Cannot open this file!\n");
exit(0);
}
printf("Please input information like this:060229 wenbiao 99 98 97\n");
p=head;
for(i=0;i<n;i++)
{q=(STU)malloc(sizeof(ST));
printf("input num:");scanf("%s",q->num);
printf("input name:");scanf("%s",q->name);
printf("input Chinese:");scanf

改成:
fwrite(q,sizeof(ST),1,fp);
不应该不行的吧?

----------------
fwrite(q,sizeof(STU),10,fp);
==>>
fwrite(q,sizeof(ST),1,fp);

STU是个指针类型,应该用sizeof(ST);
另外,fwrite第三个参数是写的个数,应该为1.

虽然是测试程序,不过也要写个释放内存的啊。

错误地方:
将fwrite(q,sizeof(STU),10,fp); 改为
fwrite((char *)q,sizeof(STU),10,fp); 就可以了
我都已经测试通过了.
是不是你在读取文件的时候方法不对.我是按如下方法读取的
int fd;
fd = open("STUDENT.TXT", O_RDONLY);
char buf[256];
int len;
memset(buf, 0, 256);
len = read(fd, buf, 256);
ST st; memset((char *)&st, 0, sizeof(ST));
memcpy((char *)&st, buf, len);
close(fd);

下面为运行结果:
Please input number of node:1
Input date:
Please input information like this:060229 wenbiao 99 98 97
input num:23
input name:wwwww
input Chinese:1
input English:2
input Math:3
读取出来的结果为p st
$1 = {num = "23\000\000", name = "pengsong