为什么最后一个重复?

 

#include <stdio.h>
#include <stdlib.h>

struct student{
	long num;
	int score;
	char name[10];
};

int main()
{
	struct student p,*stu=&p;
	FILE *fp;
	if((fp=fopen("a.dat","wb+"))==NULL){
		printf("不能打开文件!\n");
		exit(0);
	}
	printf("请输入学生学号、姓名和成绩(成绩为负数时结束):\n");
	scanf("%ld%s%d",&stu->num, stu->name, &stu->score);
	while(stu->score>=0){
		fwrite(stu,sizeof(p),1,fp);
		scanf("%ld%s%d",&stu->num, stu->name, &stu->score);
	}
	fseek(fp,0L,0);
	printf("输入文件如下:\n");
	while(!feof(fp))
	{
		fread(stu,sizeof(p),1,fp);
		printf("%ld %s %d\n",stu->num,stu->name,stu->score);
	}
	return 0;
}

#include <stdio.h>
#include <stdlib.h>

struct student{
	long num;
	int score;
	char name[10];
};

int main()
{
	struct student p,*stu=&p;
	FILE *fp;
	if((fp=fopen("a.dat","wb+"))==NULL){
		printf("不能打开文件!\n");
		exit(0);
	}
	printf("请输入学生学号、姓名和成绩(成绩为负数时结束):\n");
	scanf("%ld%s%d",&stu->num, stu->name, &stu->score);
	while(stu->score>=0){
		fwrite(stu,sizeof(p),1,fp);
		scanf("%ld%s%d",&stu->num, stu->name, &stu->score);
	}
	fseek(fp,0L,0);
	printf("输入文件如下:\n");
	fread(stu,sizeof(p),1,fp);
	while(!feof(fp))
	{
		printf("%ld %s %d\n",stu->num,stu->name,stu->score);
		fread(stu,sizeof(p),1,fp);
	}
	return 0;
}

改成这个后就不重复了???(改变了了fread的位置

#include <stdio.h>


#include <stdlib.h>


 


struct student{


	long num;


	int score;


	char name[10];


};


 


int main()


{


	struct student p,*stu=&p;


	FILE *fp;


	if((fp=fopen("a.dat","wb+"))==NULL){


		printf("不能打开文件!\n");


		exit(0);


	}


	printf("请输入学生学号、姓名和成绩(成绩为负数时结束):\n");





	while(stu->score>=0){

		scanf("%ld%s%d",&stu->num, stu->name, &stu->score);
		fwrite(stu,sizeof(p),1,fp);


		


	}


	fseek(fp,0L,0);


	printf("输入文件如下:\n");


	while(1)


	{


		fread(stu,sizeof(p),1,fp);
		if( feof(fp) )
		      {
		          break ;
		      }

		printf("%ld %s %d\n",stu->num,stu->name,stu->score);


	}


	return 0;


}

 

feof用检测流上的文件结束符,其返回值有两种情况:如果遇到文件结束,函数值为非零值,否则函数值为0

还有输入的地方也有逻辑问题