fread函数和fwrite函数
size_t fread(void *buffer, size_t size, size_t count, FILE *fp)
从文件fp中读入count次,每次读size字节,读入的信息存在buffer指针指向的缓冲区。函数返回值等于实际读入的次数(可能少于count)。
size_t fwrite(void *buffer, size_t size, size_t count, FILE *fp):
将buffer地址开始的信息,写入count次,每次写size字节至文件fp中。函数返回值等于实际写入的次数(可能少于count)。
fread与fwrite可以从一个文件中读出一个结构,并直接付给结构体。
[例]、结构体类型数据。
struct student_type
{
char name[10];
int num;
int age;
char addr[30];
}stu[40];
写入文件:
for(i=0; i<40; i++) /* 每次写一个学生 */
fwrite(&stu[i], sizeof(struct student_type), 1, fp);
或:写一次全部(因为它有缓冲区,所以只访问硬盘一次)
fwrite(stu, sizeof(struct student_type), 40, fp);
从磁盘文件读出:
for(i=0; i<40; i++)
fread(&stu[i], sizeof(struct student_type), 1, fp);
或:
fread(&stu[i], sizeof(struct student_type), 40, fp);
[例12.3] 从键盘上输入一批学生数据,然后存储到磁盘上。
#include "stdio.h"
#define SIZE 4
struct student_type
{
char name[10];
int num;
int age;
char addr[15];
}stud[SIZE];
void save(); /* 原型 */
void load(); /* 原型 */
void main()
{ int i;
for(i=0; iSIZE; i++) /* 从键盘读入数据 */
scanf("%s%d%d%s",
stud[i].name, &stud[i].num, &stud[i].age, stud[i].addr);
save(); /* 存盘 */
load(); /* 从盘读出 */
for(i=0; iSIZE; i++) /* 屏幕上显示 */
printf("%-10s%4d%4d%-15s\n", stud[i].name, stud[i].num, stud[i].age, stud[i].addr);
}
void save()
{ FILE *fp;
int i;
if ((fp=fopen("stu_list", "wb"))==NULL)
{
printf("can not open file\n";
exit(0);
}
for(i=0; iSIZE; i++)
if (fwrite(&stud[i], sizeof(struct student_type), 1, fp) != 1)
printf("file read error\n");
}
void load()
{ FILE *fp;
int i;
if ((fp=fopen("stu_list", "rb"))==NULL)
{
printf("can not open file\n";
return;
}
for(i=0; iSIZE; i++)
if (fread(&stud[i], sizeof(struct student_type), 1, fp) != 1)
{
if (feof(fp)) return;
printf("file read error\n");
}
}