#include <stdio.h>
#include <string.h>
/*
C语言文件操作就是调用库中的函数
fwrite
size_t : unsigned int
size_t fwrite(void const* _Buffer, // 要写的内容首地址
size_t size, //写的大小
size_t cout, //写几次
FILE* _Stream //写到那个文件中去
);
fread
size_t fread(void const* _Buffer, // 读的内容存到那个位置(那个位置的首地址)
size_t size, //读的大小
size_t cout, //读几次
FILE* _Stream //读的是那个文件
);
*/
struct MM
{
char name[20];
int age;
double score;
};
void writeToFile(const char* fileName, struct MM mmArray[], int arrayNum)
{
FILE* write = fopen(fileName, "w");
//No.1 一次写一个结构体变量的内存
//for (int i = 0; i < arrayNum; i++)
//{
// fwrite(&mmArray[i], sizeof(struct MM), 1, write);
//}
//No.2 sizeof(struct MM)*arrayNum;
fwrite(mmArray, sizeof(struct MM), arrayNum, write);
fclose(write);
}
void readFromFile(const char* fileName, struct MM readArray[])
{
FILE* read = fopen(fileName, "r");
//第一种读方式
//int i = 0;
//while (1)
//{
// fread(&readArray[i], sizeof(struct MM), 1, read);
// if (feof(read))
// {
// break;
// }
// printf("%s\t%d\t%.1lf\n", readArray[i].name, readArray[i].age, readArray[i].score);
// i++;
//}
fread(readArray, sizeof(struct MM), 3, read);
fclose(read);
}
void printMM(struct MM Array[], int arrayNum)
{
for (int i = 0; i < arrayNum; i++)
{
printf("%s\t%d\t%.1lf\n", Array[i].name, Array[i].age, Array[i].score);
}
}
int main()
{
struct MM mmArray[] = { "张三",18,1001.1,"李四",29,1002.2,"王五",32,1004.3};
writeToFile("mm.txt", mmArray, 3);
struct MM mmTemp[3];
readFromFile("mm.txt", mmTemp);
printMM(mmTemp,3);
return 0;
}
文件的二进制读写(完整版)
最新推荐文章于 2024-09-14 14:44:44 发布