Skip to content

Instantly share code, notes, and snippets.

Created October 13, 2016 15:40
Show Gist options
  • Save anonymous/eeb56c5cea247d77c1cb42567a6d5cac to your computer and use it in GitHub Desktop.
Save anonymous/eeb56c5cea247d77c1cb42567a6d5cac to your computer and use it in GitHub Desktop.
Works way to update binary (harder then you think)
#include <stdio.h>
#include <stddef.h>
typedef struct {
char name[128];
int max_hp;
int current_hp;
} Charactor;
#define SAVE_FILENAME "gamedata.bin"
int main()
{
int new_max_hp = 9999;
FILE *fp = fopen(SAVE_FILENAME, "r+b");
int www;
if (!fp) {
perror(NULL);
return 1;
}
size_t max_hp_offset = offsetof(Charactor, max_hp),
max_hp_size = sizeof(int),
max_hp_remaning = sizeof(Charactor) - max_hp_offset - max_hp_size;
printf("%d %d %d\n", max_hp_offset, max_hp_size, max_hp_remaning);
while (fread(&www, sizeof(int), 1, fp)) { //triggering EOF. Not the best way, but meh.
fseek(fp, max_hp_offset - sizeof(int), SEEK_CUR);
fwrite(&new_max_hp, max_hp_size, 1, fp);
fseek(fp, max_hp_remaning, SEEK_CUR);
}
fclose(fp);
return 0;
}
#include <stdio.h>
#include <stddef.h>
typedef struct {
char name[128];
int max_hp;
int current_hp;
} Charactor;
#define SAVE_FILENAME "gamedata.bin"
int main()
{
FILE *fp = fopen(SAVE_FILENAME, "r+b");
Charactor c;
if (!fp) {
perror(NULL);
return 1;
}
while (fread(&c, sizeof(Charactor), 1, fp)) {
c.max_hp = 9999;
fseek(fp, -sizeof(Charactor), SEEK_CUR);
fwrite(&c, sizeof(Charactor), 1, fp);
fflush(fp);
}
fclose(fp);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment