在 C 语言 中,我们可以使用 fwrite 函数实现将一个 结构体 写入到 文件 中,还可以使用 fread 函数实现将写入到文件的结构体读取出来。
使用 fwrite 函数写入结构体,使用 fread 函数读取结构体
#include <stdio.h>
#include <stdlib.h>
struct Student
{
char name[10];
int age;
float score;
};
int main()
{
printf("嗨客网(www.haicoder.net)\n\n");
// 定义结构体
struct Student students[3];
// 输入学生信息
int i = 0;
for(i = 0; i < 3; i++)
{
printf("Please input student %d name: ", i+1);
scanf("%s", students[i].name);
printf("Please input student %d age: ", i+1);
scanf("%d", &students[i].age);
printf("Please input student %d score: ", i+1);
scanf("%f", &students[i].score);
}
// 打开文件
FILE *fp = NULL;
if ( (fp = fopen("c:\\haicoder.txt", "rb+")) == NULL )
{
puts("Open file failed\n");
return;
}
else
{
puts("Open file success\n");
}
//写入结构体到文件
fwrite(students, sizeof(struct Student), 3, fp);
puts("Write file success\n");
//移动文件指针到文件头
rewind(fp);
// 读取文件内容到结构体
struct Student retStudents[3];
if (fread(retStudents, sizeof(struct Student), 3, fp) == NULL)
{
puts("Read file error\n");
}
else
{
printf("Read file success\n");
}
// 输出读取到的文件内容
i = 0;
for(i = 0; i < 3; i++)
{
printf("Student %d Name:%s, Age:%d, Score:%.2f\n", i+1, retStudents[i].name, retStudents[i].age, retStudents[i].score);
}
fclose(fp);
return 0;
}
程序运行后,控制台输出如下:
我们首先,定义了一个 Student 结构体,该结构体有三个成员,分别为一个 字符串 类型的 name,一个 int 类型 的 age,和一个 float 类型 的 score。
接着,我们定义了一个结构体 数组,该数组有三个成员,我们使用了 for 循环 加上 scanf 函数输入了结构体信息,同时,我们使用了 fopen 函数打开了文件,并使用 fwrtie 将结构体数组写入到文件中。
最后,我们使用了 rewind 函数,将文件指针移动到了文件的开始,并使用 fread 读取了整个文件的内容到结构体数组中,并使用 for 循环加上 printf 打印了整个文件的内容。
在 C 语言中,我们可以使用 fwrite 函数实现将一个结构体写入到文件中,还可以使用 fread 函数实现将写入到文件的结构体读取出来。