Browse Source

* imdb_open() : only open & better error handling

master
Alex 'AdUser' Z 10 years ago
parent
commit
64a717f4eb
  1. 41
      src/database.c
  2. 2
      src/database.h

41
src/database.c

@ -73,7 +73,6 @@ int imdb_init(imdb_t *db, const char *path)
int imdb_open(imdb_t *db, const char *path) int imdb_open(imdb_t *db, const char *path)
{ {
int init = 0;
ssize_t bytes = 0; ssize_t bytes = 0;
struct stat st; struct stat st;
char buf[IMDB_REC_LEN] = "\0"; char buf[IMDB_REC_LEN] = "\0";
@ -85,34 +84,38 @@ int imdb_open(imdb_t *db, const char *path)
db->fd = -1; db->fd = -1;
errno = 0; errno = 0;
if (stat(path, &st) == -1 && errno == ENOENT) { if (stat(path, &st) == -1) {
init = 1; db->errstr = strerror(errno);
return -1;
} }
errno = 0; errno = 0;
if ((db->fd = open(path, OPEN_FLAGS, 0644)) == -1) { if ((db->fd = open(path, OPEN_FLAGS)) == -1) {
db->errstr = strerror(errno); db->errstr = strerror(errno);
return -1; return -1;
} }
db->path = path; db->path = path;
memset(buf, 0x0, IMDB_REC_LEN); memset(buf, 0x0, IMDB_REC_LEN);
if (init) { DB_SEEK(db, 0);
snprintf((char *) buf, IMDB_REC_LEN, imdb_hdr_fmt, IMDB_VERSION, "M-R"); DB_READ(db, buf, IMDB_REC_LEN);
DB_SEEK(db, 0); if (bytes != IMDB_REC_LEN) {
DB_WRITE(db, buf, IMDB_REC_LEN); db->errstr = "Empty or damaged database file";
return -1;
if (bytes != IMDB_REC_LEN) }
return -1; if (memcmp("IMDB", buf, 4) != 0) {
memcpy(db->caps, "M-R", sizeof(char) * 3); db->errstr = "Not a database file";
} else { return -1;
DB_SEEK(db, 0); }
DB_READ(db, buf, IMDB_REC_LEN); if (atoi(buf + 6) != IMDB_VERSION) {
if (bytes != IMDB_REC_LEN) db->errstr = "Database version mismatch";
return -1; return -1;
memcpy(db->caps, buf + 16, sizeof(char) * 8); }
if (memcmp("CAPS", buf + 10, 4) != 0) {
db->errstr = "Can't read database capabilities";
return -1;
} }
memcpy(db->caps, buf + 16, sizeof(char) * 8);
return 0; return 0;
} }

2
src/database.h

@ -3,7 +3,7 @@
#define IMDB_REC_LEN 48 #define IMDB_REC_LEN 48
#define IMDB_VERSION 2 #define IMDB_VERSION 2
#define OPEN_FLAGS O_CREAT | O_RDWR #define OPEN_FLAGS O_RDWR
typedef struct { typedef struct {
int fd; int fd;

Loading…
Cancel
Save