変数名の整理
[YACASL2.git] / src / cerr.c
1 #include "cerr.h"
2
3 /* mallocを実行し、メモリを確保できない場合は */
4 /* エラーを出力して終了 */
5 void *malloc_chk(size_t size, char *tag)
6 {
7     void *p;
8
9     if((p = malloc(size)) == NULL) {
10         fprintf(stderr, "%s: cannot allocate memory\n", tag);
11         exit(-1);
12     }
13     return p;
14 }
15
16 /* 現在のエラー */
17 CERR *cerr;
18
19 /* エラーリスト */
20 CERRLIST *cerrlist;
21
22 /* エラーリストを作成・追加する */
23 bool addcerrlist(int newerrc, CERR newerrv[])
24 {
25     int i;
26     CERRLIST *p, *q;
27
28     assert(newerrc > 0 && newerrv != NULL);
29     if(cerrlist == NULL) {
30         p = cerrlist = malloc_chk(sizeof(CERRLIST), "cerrlist");
31     } else {
32         for(p = cerrlist; p != NULL; p = p->next) {
33             q = p;
34         }
35         p = q->next = malloc_chk(sizeof(CERRLIST), "cerrlist.next");
36     }
37     for(i = 0; i < newerrc; i++) {
38         p->cerr = &(newerrv[i]);
39         p->next = malloc_chk(sizeof(CERRLIST), "cerrlist.next");
40         q = p;
41         p = p->next;
42     }
43     q->next = NULL;
44     return true;
45 }
46
47 /* 現在のエラーを設定する */
48 void setcerr(int num, const char *str)
49 {
50     cerr->num = num;
51     cerr->msg = malloc_chk(CERRMSGSIZE + 1, "cerr.msg");
52     if(str != NULL && strlen(str) <= CERRSTRSIZE) {
53         sprintf(cerr->msg, "%s: %s", str, getcerrmsg(cerr->num));
54     } else {
55         strcpy(cerr->msg, getcerrmsg(cerr->num));
56     }
57 }
58
59 /* エラーリストから、エラー番号に対応するメッセージを返す */
60 char *getcerrmsg(int num)
61 {
62     CERRLIST *p;
63
64     for(p = cerrlist; p != NULL; p = p->next) {
65         if(num == p->cerr->num) {
66             return p->cerr->msg;
67         }
68     }
69     return "unkown error";
70 }
71
72 /* エラーリストと現在のエラーを解放する */
73 void freecerr()
74 {
75     CERRLIST *p = cerrlist, *q;
76
77     /* エラーリストを解放 */
78     while(p != NULL) {
79         q = p->next;
80         free(p);
81         p = q;
82     }
83     /* 現在のエラーを解放 */
84     free(cerr);
85 }