fwrite
#include<stdio.h>
struct S
{
char arr[20];
int age;
double f;
};
int main()
{
struct S s = { "张三",15,2.13 };
FILE* f = fopen("text.txt", "wb");
if (f==NULL)
{
return 0;
}
//从结构体s中将1个大小为sizeof(struct S)的数据写入到f中
fwrite(&s, sizeof(struct S), 1, f);
fclose(f);
f = NULL;
return 0;
}
fread
#include<stdio.h>
struct S
{
char arr[20];
int age;
double f;
};
int main()
{
struct S s = { 0 };
FILE* f = fopen("text.txt", "rb");
if (f == NULL)
{
return 0;
}
//将f中的数据 将1个大小为sizeof(struct S)的数据 赋值给结构体s
fread(&s, sizeof(struct S), 1, f);
printf("%s %d %lf", s.arr, s.age, s.f);
fclose(f);
f = NULL;
return 0;
}