chiark / gitweb /
Fix remote invocation
[ypp-sc-tools.main.git] / pctb / common.c
1 /*
2  * Utility functions
3  */
4 /*
5  *  This is part of ypp-sc-tools, a set of third-party tools for assisting
6  *  players of Yohoho Puzzle Pirates.
7  * 
8  *  Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
9  * 
10  *  This program is free software: you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation, either version 3 of the License, or
13  *  (at your option) any later version.
14  * 
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  * 
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  * 
23  *  Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
24  *  are used without permission.  This program is not endorsed or
25  *  sponsored by Three Rings.
26  */
27
28 #include "common.h"
29
30 void *mmalloc(size_t sz) {
31   void *r;
32   if (!sz) return 0;
33   sysassert( r= malloc(sz) );
34   return r;
35 }
36 void *mrealloc(void *p, size_t sz) {
37   assert(sz);
38   void *r;
39   sysassert( r= realloc(p,sz) );
40   return r;
41 }
42
43
44 FILE *dbfile;
45 static const char *path;
46
47 int dbfile_open(const char *tpath) {
48   assert(!dbfile);
49   path= tpath;
50   dbfile= fopen(path,"r");
51   if (dbfile) return 1;
52   sysassert(errno==ENOENT);
53   return 0;
54 }  
55
56 #define dbassertgl(x) ((x) ? (void)0 : dbfile_assertfail(file,line,#x))
57
58 void dbfile_getsline(char *lbuf, size_t lbufsz, const char *file, int line) {
59   errno=0;
60   char *s= fgets(lbuf,lbufsz,dbfile);
61   sysassert(!ferror(dbfile));
62   dbassertgl(!feof(dbfile));
63   assert(s);
64   int l= strlen(lbuf);
65   dbassertgl(l>0);  dbassertgl(lbuf[--l]=='\n');
66   lbuf[l]= 0;
67 }
68
69 void dbfile_close(void) {
70   if (!dbfile) return;
71   sysassert(!ferror(dbfile));
72   sysassert(!fclose(dbfile));
73   dbfile= 0;
74 }
75
76 int dbfile_vscanf(const char *fmt, va_list al) {
77   int r= vfscanf(dbfile,fmt,al);
78   sysassert(!ferror(dbfile));
79   return r;
80 }
81
82 int dbfile_scanf(const char *fmt, ...) {
83   va_list al;
84   va_start(al,fmt);
85   int r= dbfile_vscanf(fmt,al);
86   va_end(al);
87   return r;
88 }
89
90 void dbfile_assertfail(const char *file, int line, const char *m) {
91   fatal("Error in database file %s at byte %ld:\n"
92         " Requirement not met at %s:%d:\n"
93         " %s",
94         path,(long)ftell(dbfile), file,line, m);
95 }