calisto-20000323/
calisto-20000323/lib/
calisto-20000323/lib/etc/
calisto-20000323/lib/players/
calisto-20000323/lib/text/
calisto-20000323/log/
/*
 Calisto (c) 1998-2000 Peter Howkins, Matthew Howkins, Simon Howkins

 $Id: playerdb.c,v 1.5 2000/01/10 22:23:01 peter Exp $

 $Log: playerdb.c,v $
 Revision 1.5  2000/01/10 22:23:01  peter
 Now uses STRNCOPY and STRNAPPEND

 Revision 1.4  2000/01/02 16:08:21  peter
 Changed prototypes, and return values of load and save player
 Added improved error handling to save

 Revision 1.3  1999/12/29 20:25:33  peter
 Changed PLAYERPATH to literal "lib/players/". Removed #include "cfg.h"

 Revision 1.2  1999/12/18 17:21:09  peter
 changed config.h to cfg.h

 Revision 1.1  1999/11/29 22:04:40  peter
 Initial revision


 */
static char rcsid[] = "$Id: playerdb.c,v 1.5 2000/01/10 22:23:01 peter Exp $";

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "config.h"
#include "globals.h"
#include "library.h"
#include "strplus.h"
#include "structs.h"

#define CURRENT_VERSION   1

int load_player(character *c, const char *name) 
{
  int version;
  FILE *fd;
  char path[256];
  char n[MAX_NAME_LENGTH+1];

  STRNCOPY(n, name, sizeof(n));
  strlower(n);

  STRNCOPY(path, "lib/players/", sizeof(path));
  STRNAPPEND(path, n, sizeof(path));

  fd = fopen(path, "r");
  if (fd == NULL) {
    /* error has occurred do something */
    log(debug, "Error occured loading player '%s'", name);
    return 1;
  }
  /* Actually read the file */
  fscanf(fd, "%d\n", &version);
  switch(version) {
    case 1:
      fscanf(fd, "%s %s\n", c->name, c->password);
      /* if fgets finds a \n (it should do), we have to remove it */
      fgets(c->prompt, MAX_PROMPT_LENGTH + 1, fd);
      {
        char *lastchar = &c->prompt[strlen(c->prompt) - 1];

        if (*lastchar == '\n')
          *lastchar = '\0';
      }
      fscanf(fd, "%lx\n", &c->privs);
      fscanf(fd, "%lu\n", &c->prevtime);
      break;
  }
  fclose(fd);
  return 0;
}

int save_player(const character *c, const char *name)
{
  FILE *fd;
  char path[256];
  char n[MAX_NAME_LENGTH+1];
  time_t now;
  unsigned long howlong;

  STRNCOPY(n, name, sizeof(n));
  strlower(n);

  STRNCOPY(path, "lib/players/", sizeof(path));
  STRNAPPEND(path, n, sizeof(path));

  fd = fopen(path, "w+");
  if (fd == NULL) {
    /* error has occurred do something */
    log(debug, "Failed to save character %s to %s", c->name, path);
    return 1;
  }
  /* Actually write the file */
  /* put on version stamp */
  fprintf(fd, "%d\n", CURRENT_VERSION);
  fprintf(fd, "%s %s\n", c->name, c->password);
  fprintf(fd, "%s\n", c->prompt);
  fprintf(fd, "%lx\n", c->privs);
  now = time(NULL);
  howlong = (unsigned long) difftime(now, c->logintime);
  fprintf(fd, "%lu\n", c->prevtime + howlong);
  fclose(fd);
  return 0;
}