エラーをリストで格納し、分散して追加するように修正
[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 bool addcerrlist(int newerrc, CERRARRAY newerrv[])
14 {
15     int i;
16     CERRLIST *p, *q;
17
18     assert(newerrc > 0 && newerrv != NULL);
19     if(cerr != NULL) {
20         p = cerr;
21         while (p != NULL) {
22             q = p;
23             p = p->next;
24         }
25         if((p = q->next = malloc(sizeof(CERRLIST *))) == NULL) {
26             goto addcerrlisterr;
27         }
28     } else if((p = cerr = malloc(sizeof(CERRLIST *))) == NULL) {
29         goto addcerrlisterr;
30     }
31     for(i = 0; i < newerrc; i++) {
32         p->err = &(newerrv[i]);
33         if((p->next = malloc(sizeof(CERRLIST *))) == NULL) {
34             goto addcerrlisterr;
35         }
36         q = p;
37         p = p->next;
38     }
39     q->next = NULL;
40     return true;
41 addcerrlisterr:
42     fprintf(stderr, "addcerrlist: cannot allocate memory\n");
43     exit(-1);
44 }
45
46 /* エラー番号とエラーメッセージを設定する */
47 void setcerr(int num, const char *str)
48 {
49     cerrno = num;
50     cerrmsg = malloc(CERRMSGSIZE + 1);
51     if(str != NULL && strlen(str) <= CERRSTRSIZE) {
52         sprintf(cerrmsg, "%s: %s", str, getcerrmsg(cerrno));
53     } else {
54         strcpy(cerrmsg, getcerrmsg(cerrno));
55     }
56 }
57
58 /* リストから、エラー番号に対応するメッセージを返す */
59 char *getcerrmsg(int num)
60 {
61     CERRLIST *p;
62
63     for(p = cerr; p != NULL; p = p->next) {
64         if(num == p->err->num) {
65             return p->err->msg;
66         }
67     }
68     return "unkown error";
69 }
70
71 /* エラーを解放する */
72 void freecerr()
73 {
74     assert(cerrno > 0);
75     cerrno = 0;
76     if(strlen(cerrmsg) > 0) {
77         free(cerrmsg);
78     }
79 }