C语言课程设计——文件基本操作3

/*
文件的格式化读写
fprintf(文件指针,格式字符串,写入列表)
fscanf(文件指针,格式字符串,读出列表)

文件一般为:.dat或.rec

文件打开以rb或rw方式打开


对于结构体通常用下面的函数
fread(地址, 元素的大小, 元素个数, 文件指针)
fwrite(buffer, size, count, fp)


struct student{
	int num;
	char name[32];
}stu[5];
for (int i=0; i<5; i++){
	fwrite(&stu[i], sizeof(struct student), 1, fp);
}
fwrite(stu, sizeof(struct student), 5, fp);
for (int i=0; i<5; i++)
	fread(&stu[i], sizeof(struct student), 1, fp);
*/


#include 
#include 
#include 
typedef struct{
	char name[32];
	char num[32];
	int age;
	char address[32];
}student;
student stu[6];

void save()
{
	FILE *fp;
	fp=fopen("D://stu.dat", "wb");
	if (fp==NULL){
		printf("error\n");
		exit(-1); 
	}
	for (int i=1; i<=5; i++){
		fwrite(&stu[i], sizeof(student), 1, fp);
	}
	fclose(fp);
}
void load()
{
	FILE *fp;
	fp=fopen("D://stu.dat", "rb");
	if (fp==NULL){
		printf("error\n");
		exit(-1); 
	}
	for (int i=1; i<=5; i++){
		fread(&stu[i], sizeof(student), 1, fp);
		printf("%s %s %d %s\n", stu[i].name, stu[i].num, stu[i].age, stu[i].address);
	}
	fclose(fp);
}
int main()
{
	printf("姓名 学号 年龄 地址:\n");
	for (int i=1; i<=5; i++)
		scanf("%s%s%d%s", stu[i].name, stu[i].num, &stu[i].age, stu[i].address);
	for (int i=1; i<=4; i++){
		for (int j=1; j<=5-i; j++){
			if (strcmp(stu[j].num, stu[j+1].num)>0){
				student tmp;
				tmp=stu[j];
				stu[j]=stu[j+1];
				stu[j+1]=tmp;
			}
		}
	}
	save();
	load();
	return 0;
}

你可能感兴趣的:(课程设计/实践)