文件与结构体

来源:互联网 发布:mac照片怎么批量删除 编辑:程序博客网 时间:2024/06/05 04:27
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#define LEN 3
struct Student
{
int num;
char name[20];
int age;
char addr[15];
}stu[LEN];  //定义全局结构体数组;


void save(struct Student stud[])
{
FILE *fp;
int i = 0;
if ((fp = fopen("stu.dat", "wb")) == NULL)
{
printf("can't open the file.\n");
return;
}
for (i = 0; i < LEN; i++)
{
if (fwrite(&stud[i], sizeof(struct Student), 1, fp) != 1)
//这里的写文件函数fwrite()是以二进制方式进行写的
printf("file write error!\n");
}
fclose(fp);
}
void print()
{
FILE *fp;
if ((fp = fopen("stu.dat", "rb")) == NULL)
{
printf("can't open the file.\n");
return;
}
int i;
for (i = 0; i < LEN; i++)
{
fread(&stu[i], sizeof(struct Student), 1, fp);
//这里的读文件函数fread()是以二进制方式进行读的
printf("%-5d%-25s%-3d%-20s\n", stu[i].num, stu[i].name, stu[i].age, stu[i].addr);
}
fclose(fp);
}
int main()
{
int i = 0;
for (i = 0; i < LEN; i++)
{
printf("请输入第 %d 个学生的信息(学号,姓名,年龄和地址):\n", i + 1);
scanf("%d %s %d %s", &stu[i].num, stu[i].name, &stu[i].age, stu[i].addr);
}
save(stu);
print();
return 0;
}
0 0
原创粉丝点击