C语言结构体读写文件
时间: 2024-12-09 16:12:17 浏览: 59
在C语言中,结构体(struct)是一种用户自定义的数据类型,可以将不同类型的数据组合在一起。要将结构体读写文件,通常使用文件操作函数如`fread`和`fwrite`。以下是一些基本的步骤和示例代码:
### 写入结构体到文件
1. 打开文件:使用`fopen`函数以写模式打开文件。
2. 写入数据:使用`fwrite`函数将结构体数据写入文件。
3. 关闭文件:使用`fclose`函数关闭文件。
```c
#include <stdio.h>
#include <stdlib.h>
struct Person {
char name[50];
int age;
};
int main() {
struct Person person = {"Alice", 30};
FILE *file = fopen("person.dat", "wb");
if (file == NULL) {
printf("无法打开文件!\n");
return 1;
}
fwrite(&person, sizeof(struct Person), 1, file);
fclose(file);
printf("结构体数据已写入文件。\n");
return 0;
}
```
### 从文件读取结构体
1. 打开文件:使用`fopen`函数以读模式打开文件。
2. 读取数据:使用`fread`函数从文件中读取结构体数据。
3. 关闭文件:使用`fclose`函数关闭文件。
```c
#include <stdio.h>
#include <stdlib.h>
struct Person {
char name[50];
int age;
};
int main() {
struct Person person;
FILE *file = fopen("person.dat", "rb");
if (file == NULL) {
printf("无法打开文件!\n");
return 1;
}
fread(&person, sizeof(struct Person), 1, file);
printf("姓名: %s\n", person.name);
printf("年龄: %d\n", person.age);
fclose(file);
return 0;
}
```
### 注意事项
- 确保结构体的成员数据类型在读写过程中保持一致。
- 使用二进制模式(`"wb"`和`"rb"`)进行读写,以确保数据的正确性。
- 在实际应用中,可能需要处理文件打开失败的情况。
阅读全文
相关推荐


















