码迷,mamicode.com
首页 > 其他好文 > 详细

《用二进制方式向文件读写一组数据》

时间:2015-09-15 21:52:39      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:


/*
用二进制方式向文件读写一组数据
一般的调用方式为:
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;
}

 

《用二进制方式向文件读写一组数据》

标签:

原文地址:http://www.cnblogs.com/sun-/p/4811479.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!