匿名用户
1级
2007-03-24 回答
这要看你的代码是什么样的。
贴出我的验证代码你看看有什么不同。
有一点要注意如果你用的是TC之类的编译器,它是DOS下工作的不支持8个字符以上的长文件名,所以要用短名如:stud_r~1.txt
#include "stdio.h"
void main()
{
FILE *pf;
char str[100];
int i;
for(i=0;i<100;i++) str[i]=0;
pf=fopen("C:\\record.txt","r");
fread(str,100,100,pf);
fclose(pf);
printf("\n%s",str);
}
看了你的代码,有几处不妥修正如下:
#include
struct student
{
char stu_num[5];
char name[10];
int age;
int score;
}stu[9];
print_rec(struct student *stud); /*你的访问方法行不通,要这样*/
main()
{
i=0;
FILE *fp;
fp=fopen("C:\\stud_r~1.txt","r");/*这里一定不能放在if里面,这个赋值返回是恒为真的。*/
if(fp==NULL)
{printf("Cannot open the file\n");exit(0);}
for(i=0;i<9;i++)
fread(&stu[i],sizeof(struct student),sizeof(struct student),fp);/*第三个参数是读取的字节数所以不能是1*/
print_rec(stu);
fclose(fp);/*事情做完记得收拾工具*/
getch();
}
print_rec(struct student *stud)
{
int j;
for(j=0;j<9;j++)
printf("%7s%10s%4d%6f\n",stud[j].stu_num,stud[j].name,stud[j].age,stud[j].score);
}