printf("Bad database file or non-existent.\n");
return 1;
}
- printf("Opened the database.\n");
+ printf("Opened the database (Version %d).\n", db->version);
printf("\n");
printf("Type a command (.help) for the help\n");
printf("\n");
#include "dw_database.h"
+#include "dw_util.h"
+
#include <stdint.h>
#include <stdio.h>
-#include <string.h>
#include <stdlib.h>
+#include <string.h>
const char sig[3] = {0x7f, 'D', 'W'};
fclose(fp);
return NULL;
}
+ __dw_lockfile(fp);
+ char ptrver[2];
+ fread(ptrver, 1, 2, fp);
+ uint16_t be_ver = *(uint16_t*)(char*)ptrver;
+ uint16_t ver;
+ __dw_native_endian(be_ver, uint16_t, ver = __converted);
+ __dw_unlockfile(fp);
struct dataworks_db* db = malloc(sizeof(*db));
db->fp = fp;
+ db->version = ver;
return db;
}
#define __dw_xstr(x) #x
#define __dw_str(x) __dw_xstr(x)
+/* Converts NE to BE */
#define __dw_big_endian(arg, type, exec) \
{ \
type __original = arg; \
exec; \
}
+/* Converts BE to NE */
+#define __dw_native_endian(arg, type, exec) \
+ { \
+ type __original = arg; \
+ signed char* __ptr = (signed char*)&__original; \
+ type __converted; \
+ signed char* __converted_ptr = (signed char*)&__converted; \
+ int __i; \
+ int __endian_check = 1; \
+ char __endian = (1 == *(volatile char*)&__endian_check) ? 'L' : 'B'; \
+ for(__i = 0; __i < sizeof(type); __i++) { \
+ if(__endian == 'L') { \
+ __converted_ptr[sizeof(type) - __i - 1] = __ptr[__i]; \
+ } else { \
+ __converted_ptr[__i] = __ptr[__i]; \
+ } \
+ } \
+ exec; \
+ }
+
#ifdef __cplusplus
}
#endif
return true;
}
-bool __dw_lockfile(FILE* fp){
+bool __dw_lockfile(FILE* fp) {
+ off_t off = ftell(fp);
+ fseek(fp, 0, SEEK_SET);
#ifdef __MINGW32__
OVERLAPPED overlap = {0};
LockFileEx(fp, LOCKFILE_EXCLUSIVE_LOCK, 0, MAXDWORD, MAXDWORD, &overlap);
#else
- fseek(fp, SEEK_SET, 0);
lockf(fileno(fp), F_LOCK, 0);
#endif
+ fseek(fp, off, SEEK_SET);
return false;
}
-bool __dw_unlockfile(FILE* fp){
+bool __dw_unlockfile(FILE* fp) {
+ off_t off = ftell(fp);
+ fseek(fp, 0, SEEK_SET);
#ifdef __MINGW32__
OVERLAPPED overlap = {0};
UnlockFileEx(fp, 0, MAXDWORD, MAXDWORD, &overlap);
#else
- fseek(fp, SEEK_SET, 0);
lockf(fileno(fp), F_ULOCK, 0);
#endif
+ fseek(fp, off, SEEK_SET);
return false;
}