练习fwrite()和fread()函数的使用 方法。
fwrite()函数的作用是将一个长度为29字节的数据块送到文件中(一个student_type类型结构体变量的长度为它的成员长度之和,即10+2+2+15=29)
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include
<
stdio.h
>
#define SIZE 2
#define LEN sizeof(struct student_type)
struct student_type
{
char name[ 10 ];
int num;
int age;
char addr[ 15 ];
}stud[SIZE];
void save()
{
FILE * fp;
int i;
if ((fp = fopen( " test " , " wb " )) == NULL)
{
printf( " 无法打开文件\n " );
exit( 1 );
}
for (i = 0 ;i < SIZE;i ++ )
if (fwrite( & stud[i],LEN, 1 ,fp) != 1 )
printf( " 文件写入失败。\n " );
fclose(fp);
}
void input()
{
int i;
printf( " 姓名\t学号\t年龄\t地址\n " );
for (i = 0 ;i < SIZE;i ++ )
scanf( " %s%d%d%s " ,stud[i].name, & stud[i].num, & stud[i].age,stud[i].addr);
}
void output()
{
FILE * fp;
int i;
if ((fp = fopen( " test " , " rb " )) == NULL)
{
printf( " 无法打开文件\n " );
exit( 1 );
}
for (i = 0 ;i < SIZE;i ++ )
{
fread( & stud[i],LEN, 1 ,fp);
printf( " %-10s %4d %4d %-15s\n " ,stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
}
fclose(fp);
}
void main()
{
input();
save();
output();
}
#define SIZE 2
#define LEN sizeof(struct student_type)
struct student_type
{
char name[ 10 ];
int num;
int age;
char addr[ 15 ];
}stud[SIZE];
void save()
{
FILE * fp;
int i;
if ((fp = fopen( " test " , " wb " )) == NULL)
{
printf( " 无法打开文件\n " );
exit( 1 );
}
for (i = 0 ;i < SIZE;i ++ )
if (fwrite( & stud[i],LEN, 1 ,fp) != 1 )
printf( " 文件写入失败。\n " );
fclose(fp);
}
void input()
{
int i;
printf( " 姓名\t学号\t年龄\t地址\n " );
for (i = 0 ;i < SIZE;i ++ )
scanf( " %s%d%d%s " ,stud[i].name, & stud[i].num, & stud[i].age,stud[i].addr);
}
void output()
{
FILE * fp;
int i;
if ((fp = fopen( " test " , " rb " )) == NULL)
{
printf( " 无法打开文件\n " );
exit( 1 );
}
for (i = 0 ;i < SIZE;i ++ )
{
fread( & stud[i],LEN, 1 ,fp);
printf( " %-10s %4d %4d %-15s\n " ,stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
}
fclose(fp);
}
void main()
{
input();
save();
output();
}