Skip to content

Instantly share code, notes, and snippets.

@peat-psuwit
Forked from anonymous/myWay.c
Last active October 13, 2016 15:45
Show Gist options
  • Save peat-psuwit/f5b7cdf29684668a9bf692be3b7e4e5b to your computer and use it in GitHub Desktop.
Save peat-psuwit/f5b7cdf29684668a9bf692be3b7e4e5b 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"); //This is the mode you want.
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"); //This is the mode you want
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