I mean that a .txt takes much longer to read, a .bin is very fast to read, these are practical when it comes to building a database...
An example:
Code: Select all
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 50
#define MAX_CHARACTERS 6
#define MAX_ITEMS 100
#define MAX_DROPS 10
#define MAX_MAPS 32
typedef struct {
int id;
char name[MAX_NAME_LENGTH];
int type; // 1: Weapon, 2: Armor, 3: Potion
int value;
int weight;
} Item;
typedef struct {
int id;
char name[MAX_NAME_LENGTH];
int experience;
int health;
int attack;
int mapId;
int x;
int y;
int inventorySpace;
int level;
int inventorySize;
Item inventory[MAX_ITEMS];
} Character;
typedef struct {
int id;
char name[MAX_NAME_LENGTH];
int level;
int health;
int attack;
int experienceReward;
int mapId;
int x;
int y;
int dropCount;
struct {
Item item;
int dropRate;
} drops[MAX_DROPS];
} Monster;
typedef struct {
int id;
char name[MAX_NAME_LENGTH];
int difficulty;
int x;
int y;
} Map;
typedef struct {
char username[MAX_NAME_LENGTH];
char password[MAX_NAME_LENGTH];
int characterCount;
Character characters[MAX_CHARACTERS];
} User;
void writeUser(const User* user) {
FILE* file = fopen("save.bin", "ab");
if (!file) {
printf("Error opening binary file.\n");
exit(1);
}
fwrite(user, sizeof(User), 1, file);
fclose(file);
}
void readUsers() {
FILE* file = fopen("save.bin", "rb");
if (!file) {
printf("No saved data found.\n");
return;
}
User user;
while (fread(&user, sizeof(User), 1, file)) {
printf("Username: %s\n", user.username);
printf("Character Count: %d\n", user.characterCount);
for (int i = 0; i < user.characterCount; i++) {
printf(" Character %d: %s, Level: %d\n", i + 1, user.characters[i].name, user.characters[i].level);
}
}
fclose(file);
}
void createBinaryFile() {
FILE* file = fopen("save.bin", "wb");
if (!file) {
printf("Error creating binary file.\n");
exit(1);
}
fclose(file);
}
int main() {
createBinaryFile();
User user = {"player1", "password123", 1};
user.characters[0] = (Character){1, "Hero", 500, 100, 20, 1, 10, 10, 10, 5, 0, {}};
writeUser(&user);
printf("Data written to save.bin successfully.\n");
printf("Reading saved users:\n");
readUsers();
system("PAUSE");
return 0;
}


