C 从键盘输入4个学生的有关数据然后把他们以二进制的格式存储到磁盘文件中

//从键盘输入4个学生的有关数据
//然后把他们以二进制的格式存储到磁盘文件中
#include <stdio.h>

#define SIZE 4

void save();
void load();
struct student
{
    
    
	char name[10];
	int num;
	int age;
	char addr[15];
}stu[SIZE];

int main()
{
    
    
	int i;
	printf("Please input the student's name,num,age and address:\n");
	for(i=0;i<SIZE;i++)
	{
    
    
		scanf("%s%d%d%s",&stu[i].name,&stu[i].num,&stu[i].age,&stu[i].addr);
	}
	save();
	load();
	for(i=0;i<SIZE;i++)
	{
    
    
		printf("%s %d %d %s\n",stu[i].name,stu[i].num,stu[i].age,stu[i].addr);
	}
} 

void save()
{
    
    
	FILE *fp;
	int i;
	if(!(fp=fopen("student-list","wb")))
	{
    
    
		printf("Cannot open the file!\n");
		return;
	} 
		
	
	for(i=0;i<SIZE;i++)
	{
    
    
		if(fwrite(&stu[i],sizeof(struct student),1,fp)!=1)
		{
    
    
			printf("File write error!\n");
			fclose(fp);
		}
	}
	
}

void load()
{
    
    
	FILE *fp;
	int i;
	if(!(fp=fopen("student-list","rb")))
		printf("Cannot open the file!\n");
		return;
	for(i=0;i<SIZE;i++)
	{
    
    
		if(fread(&stu[i],sizeof(struct student),1,fp)!=1)
		{
    
    
			printf("File read error!\n");
			fclose(fp);
		}	 
	}
}

猜你喜欢

转载自blog.csdn.net/qq_48167493/article/details/120562401
今日推荐