写一段逆向结构体的代码,从文件还原结构体内容
时间: 2023-11-02 12:12:08 浏览: 33
假设我们有一个结构体定义如下:
```c
typedef struct {
int id;
char name[20];
float score;
} Student;
```
我们可以将结构体的内容写入文件中,并使用以下代码从文件中还原结构体:
```c
#include <stdio.h>
int main() {
FILE *fp;
Student s;
if ((fp = fopen("students.dat", "rb")) == NULL) {
printf("Cannot open file.\n");
return 1;
}
while (fread(&s, sizeof(Student), 1, fp) == 1) {
printf("ID: %d, Name: %s, Score: %f\n", s.id, s.name, s.score);
}
fclose(fp);
return 0;
}
```
在上面的代码中,我们使用了 `fopen` 函数打开了一个名为 `students.dat` 的二进制文件,并将文件指针保存在变量 `fp` 中。然后我们使用 `fread` 函数从文件中读取数据,并将数据存储在结构体变量 `s` 中。最后我们将 `s` 变量中的数据打印出来,即还原了结构体的内容。最后我们使用 `fclose` 函数关闭文件。