662cc6680d5b974d6fbd9700b807cc406d04f9ca
[YACASL2.git] / src / cerr.c
1 #include "cerr.h"
2
3 /* エラー番号 */
4 int cerrno = 0;
5
6 /* エラーメッセージ */
7 char *cerrmsg;
8
9 /* エラーリスト */
10 CERRLIST *cerr;
11
12 /* エラーリストを作成する */
13 void addcerrlist(int newerrc, CERRARRAY newerrv[])
14 {
15     int i;
16     CERRLIST *p = cerr, *q;
17
18     if(cerr != NULL) {
19         for(p = cerr; p != NULL; p = p->next) {
20             ;
21         }
22         if((p = malloc(sizeof(CERRLIST *))) == NULL) {
23             fprintf(stderr, "addcerrlist: cannot allocate memory\n");
24             exit(-1);
25         }
26     } else if((p = cerr = malloc(sizeof(CERRLIST *))) == NULL) {
27         fprintf(stderr, "addcerrlist: cannot allocate memory\n");
28         exit(-1);
29     }
30     for(i = 0; i < newerrc; i++) {
31         p->err = &(newerrv[i]);
32         if((p->next = malloc(sizeof(CERRLIST *))) == NULL) {
33             fprintf(stderr, "addcerrlist: cannot allocate memory\n");
34             exit(-1);
35         }
36         q = p;
37         p = p->next;
38     }
39     q->next = NULL;
40 }
41
42 /* エラー番号とエラーメッセージを設定する */
43 void setcerr(int num, const char *str)
44 {
45     cerrno = num;
46     cerrmsg = malloc(CERRMSGSIZE + 1);
47     if(str != NULL && strlen(str) <= CERRSTRSIZE) {
48         sprintf(cerrmsg, "%s: %s", str, getcerrmsg(cerrno));
49     } else {
50         strcpy(cerrmsg, getcerrmsg(cerrno));
51     }
52 }
53
54 /* リストから、エラー番号に対応するメッセージを返す */
55 char *getcerrmsg(int num)
56 {
57     CERRLIST *p;
58
59     for(p = cerr; p != NULL; p = p->next) {
60         if(num == p->err->num) {
61             return p->err->msg;
62         }
63     }
64     return "unkown error";
65 }
66
67 /* エラーを解放する */
68 void freecerr()
69 {
70     assert(cerrno > 0);
71     cerrno = 0;
72     if(strlen(cerrmsg) > 0) {
73         free(cerrmsg);
74     }
75 }