1.fwrite (binary output)
// size_t fwrite(const void* ptr, size_t size, size_t count, FILE* stream);
// const void* ptr: pointer to the data to be written
// size_t size: one element size of the data to be written
// size_t count: the number of elements of the data to be written
// FILE* stream: the file pointer pointing to the file to be written
// size_t fwrite (return value): the actual number of elements output, not necessarily equal to count
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
struct S
{
char name[20];
int age;
float score;
};
int main()
{
struct S s1 = { "zhangsan",24,93.5f };
//打开文件
FILE* pf = fopen("test.dat", "wb");
if (pf == NULL)
{
perror("fopen");
return 1;
}
//写文件
fwrite(&s1, sizeof(struct S), 1, pf);
// fwrite是以二进制形式输出(写文件),所以文件打开之后会出现部分内容(准确来说是除了字符串以外的其他类型的内容,因为字符串以二进制形式存储和以文本形式存
// 储是一样的)不认识或者乱码,因为二进制形式存储和文本形式存储是截然不同的。为解决不认识二进制形式的输出内容这一问题,我们可以再以二进制形式读取(输入)这些内容
//关闭文件
fclose(pf);
pf = NULL;
return 0;
}
2.fread (binary input)
// size_t fread(void* ptr, size_t size, size_t count, FILE* stream);
// void* ptr: Pointer to the memory block used to store the read data. This memory block can store at least count elements.
// size_t size: the size of an element of the data to be read
// size_t count: the number of elements of the data to be read
// FILE* stream: file pointer pointing to the file to be read
// size_t fread (return value): fread actual The number of elements read, if the count parameter is 5, and the number of elements actually read by fread is 3, then the return value is 3
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
struct S
{
char name[20];
int age;
float score;
};
int main()
{
struct S s2 = {0};
//打开文件
FILE* pf = fopen("test.dat", "rb");
if (pf == NULL)
{
perror("fopen");
return 1;
}
//写文件
fread(&s2, sizeof(struct S), 1, pf);
// fread是以二进制形式输入(读文件),"test.dat"是文本文件,里边存放了二进制信息,二进制信息在文本文件中我们是看不懂的(除了字符内容,字符的
// 二进制形式和文本形式是一样的),fread可以读取到文本文件中的二进制信息
printf("%s %d %f\n", s2.name, s2.age, s2.score); //zhangsan 24 93.500000
//关闭文件
fclose(pf);
pf = NULL;
return 0;
}