太自由

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理


/*
用二进制方式向文件读写一组数据
一般的调用方式为:
fread(buffer,size,count,fp);
fwrite(buffer,size,count,fp);
其中:
buffer:是一个地址,对fread来说,它是用来存放从文件读入的数据的存储区的地址。
对fwrite来说,是要把此地址开始的存储区中的数据向文件输出(以上指的是起始地址)
size:要读写的字节数
count:要读写多少个数据项(每个数据项的长度为size)
fp:FILE类型指针

从键盘输入10个学生的有关数据,然后把他们转存到磁盘上去
*/

 

 

#include<stdio.h>
#include<stdlib.h>
#define SIZE 3
struct Student_type
{
char name[10];
int num;
int age;
char addr[30];
}stu[SIZE]; //定义全局结构体数组stu,包含10个学生的数据

void save()
{
FILE *fp;
int i;
if((fp=fopen("f:\\FILE_1\\file_5.txt","wb"))==NULL)
{
printf("can't open file\n");
exit(0);
//return;
}
for(i=0;i<SIZE;i++)
{
if(fwrite(&stu[i],sizeof(struct Student_type),1,fp)!=1)
//fputs("\n",fp);
printf("file write error!\n");
}
fclose(fp);

}

void print()
{
FILE *fp;
int i;
if((fp=fopen("f:\\FILE_1\\file_5.txt","rb"))==NULL)
{
printf("can't open file!\n");
exit(0);
}
for(i=0;i<SIZE;i++)
{
fread(&stu[i],sizeof(struct Student_type),1,fp);
printf("%-10s%4d%4d%-25s\n",stu[i].name,stu[i].num,stu[i].age,stu[i].addr);
}
fclose(fp);

}

int main()
{
int i;
printf("Please enter data of students:\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();
print();
return 0;
}

 

posted on 2015-09-15 21:06  太自由  阅读(648)  评论(0编辑  收藏  举报