C语言结构体写入文件
时间: 2024-07-01 14:00:18 浏览: 245
在C语言中,结构体(struct)是一种用户自定义的数据类型,用于组合不同类型的变量。要将结构体写入文件,通常需要使用文件操作函数,如`fopen`、`fwrite`或`fprintf`。以下是一个简单的步骤:
1. 定义结构体:
```c
typedef struct {
int id;
float value;
char name[20];
} MyStruct;
```
2. 创建结构体实例:
```c
MyStruct myObj;
myObj.id = 1;
myObj.value = 3.14;
strcpy(myObj.name, "Example");
```
3. 打开文件以写入:
```c
FILE* file = fopen("output.txt", "w");
if (file == NULL) {
perror("Error opening file");
return 1;
}
```
4. 写入结构体到文件:
```c
// 使用fwrite写入结构体
size_t written = fwrite(&myObj, sizeof(MyStruct), 1, file);
if (written != 1) {
perror("Error writing to file");
fclose(file);
return 1;
}
```
或者使用`fprintf`格式化输出:
```c
fprintf(file, "%d %f %s\n", myObj.id, myObj.value, myObj.name);
```
记得在结束写入后关闭文件:
```c
fclose(file);
```
阅读全文
相关推荐















