aboutsummaryrefslogtreecommitdiff
path: root/src/data.c
blob: 0d43d3c356a8365e7604bb49daa04532daa8110a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <asm-generic/errno-base.h>
#define _GNU_SOURCE
#include "data.h"
#include "login.h"
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

int try_make_data_dirs() {
  int err = 0;
  err = mkdir("data", S_IRWXU);
  err = mkdir("data/players", S_IRWXU);

  return err;
}

int try_load_plr(char *player_name, playerc_t *plr) {
  int err = 0;
  printf("Trying to make data directories...\n");
  err = try_make_data_dirs();
  if (err) {
    switch (err) {
      // Now the errors that continue will be from I/O, which we can use to
      // figure out if the file exists in login
    case EACCES: /* No permissions***************************************/
      printf("No permissions to create directories\n");
      return -1;
    default: /* Do nothing because this is fine****************************/
      break;
    }
  }

  printf("Done, opening file.\n");

  char *fname;
  asprintf(&fname, "data/players/%s.plr", player_name);

  FILE *fp;

  if (fp = fopen(fname, "rb")) {

	  printf("Got fp\n");

	  fread(&plr->plr, sizeof(player_t), 1, fp);
  } else {
	  return 4; // File doesn't exist
  }

  printf("Read file into plr\n");
  fclose(fp);

  return err;
}

int try_write_plr(player_t *plr) {
  int err = 0;

  err = try_make_data_dirs();
  if (err) {
    switch (err) {
      // Now the errors that continue will be from I/O, which we can use to
      // figure out if the file exists in login
    case EACCES: /* No permissions***************************************/
      printf("No permissions to create directories\n");
      return -1;
    default: /* Do nothing because this is fine****************************/
      break;
    }
  }

  char *fname;
  asprintf(&fname, "data/players/%s.plr", plr->name);

  FILE *fp = fopen(fname, "wb");

  fwrite(&plr, sizeof(player_t), 1, fp);
  fclose(fp);

  return err;
}