1---
 2title: "Write and read structs to/from files in C"
 3url: write-and-read-structs-to-files-in-c.html
 4date: 2024-06-22T16:13:13+02:00
 5type: note
 6draft: false
 7tags: [c]
 8---
 9
10First let's define a shared header file for the struct definition.
11
12```c
13// struct.h
14typedef struct {
15    char name[50];
16    int health;
17    float damage;
18} Character;
19```
20
21Now lets write it to a `character.dat` file.
22
23```c
24// write.c
25#include <stdio.h>
26#include <string.h>
27
28#include "struct.h"
29
30int main(void) {
31    printf("Write struct\n");
32
33    Character ch;
34
35    strcpy(ch.name, "John Doe");
36    ch.health = 30;
37    ch.damage = 5.9;
38
39    FILE* file = fopen("character.dat", "wb");
40    if (file == NULL) {
41        perror("Error opening file");
42        return 1;
43    }
44
45    fwrite(&ch, sizeof(Character), 1, file);
46    fclose(file);
47
48    return 0;
49}
50```
51
52If we check the contents of the `character.dat` file it should look like this.
53
54```txt
55$ xxd character.dat
5600000000: 4a6f 686e 2044 6f65 0000 0000 0000 0000  John Doe........
5700000010: 0000 0000 0000 0000 0000 0000 0000 0000  ................
5800000020: 0000 0000 0000 0000 0000 0000 0000 0000  ................
5900000030: 0000 0000 1e00 0000 cdcc bc40            ...........@
60```
61
62Reading and serializing back to a struct.
63
64```c
65// read.c
66#include <stdio.h>
67
68#include "struct.h"
69
70int main(void) {
71    printf("Read struct\n");
72
73    Character ch;
74
75    FILE* file = fopen("character.dat", "rb");
76    if (file == NULL) {
77        perror("Error opening file");
78        return 1;
79    }
80
81    fread(&ch, sizeof(Character), 1, file);
82    fclose(file);
83
84    printf("Name: %s\n", ch.name);
85    printf("Health: %d\n", ch.health);
86    printf("Damage: %.1f\n", ch.damage);
87
88    return 0;
89}
90```
91