fwrite(&f,sizeof(float),1,fp); //把浮点数f写入文件
fwrite(d,sizeof(double),10,fp); //把数组d中所有数写入文件
fread(&f,sizeof(float),1,fp); //从文件中以块形式读一浮点数到变量f中
fread(d,sizeof(d),1,fp); //从文件中一次性读一个数组d大小的数据块到数组d中
简单来说就是:
fread(取数据地址,数据类型长度,数据数量,文件指针)
fwrite(待写入地址,数据类型长度,数据数量,文件指针)
示例程序:
#define _CRT_SECURE_NO_WARNINGS
#define N 5
#include<stdio.h>
#include<stdlib.h>
struct student
{
char name[20];
char num[20];
float score;
}s[N],t[N];
int main() {
FILE **fp;
int i;
if ((fp = fopen("D:\\student.dat", "wb")) == NULL)
{
printf("cannot open student.dat");
return -1;
}
for (i = 0; i < 5; i++)
{
scanf("%s%s%1f", s[i].name, s[i].num, &s[i].score);
fwrite(&s[i], sizeof(s[i]), 1, fp);
}
fclose(fp);
if ((fp = fopen("D:\\student.dat","rb")) == NULL)
{
printf("cannot open student.dat");
return -1;
}
fread(&t, sizeof(t), 1, fp);
for (i = 0; i < 5; i++)
{
printf("%s %s %1f\n", t[i].name, t[i].num, t[i].score);
}
fclose(fp);
return 0;
}
/*
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
*/