diff --git a/c-structs/.clang-format b/c-structs/.clang-format new file mode 100644 index 0000000000000000000000000000000000000000..5f0e5858e8486f9ed0471951032c497a07a45ef1 --- /dev/null +++ b/c-structs/.clang-format @@ -0,0 +1,4 @@ +BasedOnStyle: Chromium +ColumnLimit: 120 +IndentWidth: 4 + diff --git a/c-structs/Makefile b/c-structs/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..20694af43a846d0d704e561660cfa66d940fc401 --- /dev/null +++ b/c-structs/Makefile @@ -0,0 +1,13 @@ +all: write read + +write: + gcc write.c -o write + +read: + gcc read.c -o read + +clean: + -rm write + +tags: + ctags -R * diff --git a/c-structs/character.dat b/c-structs/character.dat new file mode 100644 index 0000000000000000000000000000000000000000..1a1007034aa77fcad2fbed5d152d7137e88b7680 Binary files /dev/null and b/c-structs/character.dat differ diff --git a/c-structs/read.c b/c-structs/read.c new file mode 100644 index 0000000000000000000000000000000000000000..b67974fb5e5c3593e098f9464f5f5116ef947991 --- /dev/null +++ b/c-structs/read.c @@ -0,0 +1,24 @@ +#include + +#include "struct.h" + +int main(void) { + printf("Read struct\n"); + + Character ch; + + FILE* file = fopen("character.dat", "rb"); + if (file == NULL) { + perror("Error opening file"); + return 1; + } + + fread(&ch, sizeof(Character), 1, file); + fclose(file); + + printf("Name: %s\n", ch.name); + printf("Health: %d\n", ch.health); + printf("Damage: %.1f\n", ch.damage); + + return 0; +} diff --git a/c-structs/struct.h b/c-structs/struct.h new file mode 100644 index 0000000000000000000000000000000000000000..38a0cc7b69b4c5e06979ae014bba0ad22c083d8c --- /dev/null +++ b/c-structs/struct.h @@ -0,0 +1,6 @@ +typedef struct { + char name[50]; + int health; + float damage; +} Character; + diff --git a/c-structs/write.c b/c-structs/write.c new file mode 100644 index 0000000000000000000000000000000000000000..e83531adfcb66d35beb182740fcd3b06b0e07949 --- /dev/null +++ b/c-structs/write.c @@ -0,0 +1,25 @@ +#include +#include + +#include "struct.h" + +int main(void) { + printf("Write struct\n"); + + Character ch; + + strcpy(ch.name, "John Doe"); + ch.health = 30; + ch.damage = 5.9; + + FILE* file = fopen("character.dat", "wb"); + if (file == NULL) { + perror("Error opening file"); + return 1; + } + + fwrite(&ch, sizeof(Character), 1, file); + fclose(file); + + return 0; +}