Added writing and reading structs from files

Author Mitja Felicijan <mitja.felicijan@gmail.com> 2024-06-22 20:01:14 +0200
Committer Mitja Felicijan <mitja.felicijan@gmail.com> 2024-06-22 20:01:14 +0200
Commit 134f855b537b714eb98bc1e6e1e4790b4d6491a3 (patch)
-rw-r--r-- c-structs/.clang-format 4
-rw-r--r-- c-structs/Makefile 13
-rw-r--r-- c-structs/character.dat bin 0 B -> 60 B
-rw-r--r-- c-structs/read.c 24
-rw-r--r-- c-structs/struct.h 6
-rw-r--r-- c-structs/write.c 25
6 files changed, 72 insertions, 0 deletions
diff --git a/c-structs/.clang-format b/c-structs/.clang-format
  
1
BasedOnStyle: Chromium
  
2
ColumnLimit: 120
  
3
IndentWidth: 4
  
4
  
diff --git a/c-structs/Makefile b/c-structs/Makefile
  
1
all: write read
  
2
  
  
3
write:
  
4
	gcc write.c -o write
  
5
  
  
6
read:
  
7
	gcc read.c -o read
  
8
  
  
9
clean:
  
10
	-rm write
  
11
  
  
12
tags:
  
13
	ctags -R *
diff --git a/c-structs/character.dat b/c-structs/character.dat
diff --git a/c-structs/read.c b/c-structs/read.c
  
1
#include <stdio.h>
  
2
  
  
3
#include "struct.h"
  
4
  
  
5
int main(void) {
  
6
    printf("Read struct\n");
  
7
  
  
8
    Character ch;
  
9
  
  
10
    FILE* file = fopen("character.dat", "rb");
  
11
    if (file == NULL) {
  
12
        perror("Error opening file");
  
13
        return 1;
  
14
    }
  
15
  
  
16
    fread(&ch, sizeof(Character), 1, file);
  
17
    fclose(file);
  
18
  
  
19
    printf("Name: %s\n", ch.name);
  
20
    printf("Health: %d\n", ch.health);
  
21
    printf("Damage: %.1f\n", ch.damage);
  
22
  
  
23
    return 0;
  
24
}
diff --git a/c-structs/struct.h b/c-structs/struct.h
  
1
typedef struct {
  
2
    char name[50];
  
3
    int health;
  
4
    float damage;
  
5
} Character;
  
6
  
diff --git a/c-structs/write.c b/c-structs/write.c
  
1
#include <stdio.h>
  
2
#include <string.h>
  
3
  
  
4
#include "struct.h"
  
5
  
  
6
int main(void) {
  
7
    printf("Write struct\n");
  
8
  
  
9
    Character ch;
  
10
  
  
11
    strcpy(ch.name, "John Doe");
  
12
    ch.health = 30;
  
13
    ch.damage = 5.9;
  
14
  
  
15
    FILE* file = fopen("character.dat", "wb");
  
16
    if (file == NULL) {
  
17
        perror("Error opening file");
  
18
        return 1;
  
19
    }
  
20
  
  
21
    fwrite(&ch, sizeof(Character), 1, file);
  
22
    fclose(file);
  
23
  
  
24
    return 0;
  
25
}