Merge branch 'master' into yaz-744
[yaz-moved-to-github.git] / src / errno.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) Index Data
3  * See the file LICENSE for details.
4  */
5
6 /**
7  * \file errno.c
8  * \brief errno utilities
9  *
10  * This file unlike other files in YAZ core is thread-aware, due to
11  * the use errno.
12  */
13 #if HAVE_CONFIG_H
14 #include <config.h>
15 #endif
16
17 #ifndef _REENTRANT
18 #define _REENTRANT
19 #endif
20
21 #include <stdlib.h>
22 #include <string.h>
23 #include <errno.h>
24 #include <stddef.h>
25 #include <yaz/errno.h>
26
27 #ifdef WIN32
28 #include <windows.h>
29 #endif
30
31 int yaz_errno(void)
32 {
33     return errno;
34 }
35
36 void yaz_set_errno(int v)
37 {
38     errno = v;
39 }
40
41 void yaz_strerror(char *buf, size_t bufsz)
42 {
43 #ifdef WIN32
44     DWORD err;
45 #endif
46     char *cp;
47 #ifdef WIN32
48     err = GetLastError();
49     if (err)
50     {
51         FormatMessage(
52                 FORMAT_MESSAGE_FROM_SYSTEM,
53                 NULL,
54                 err,
55                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default lang */
56                 (LPTSTR) buf,
57                 bufsz-1,
58                 NULL);
59     }
60     else
61         *buf = '\0';
62 #else
63 /* UNIX */
64 #if HAVE_STRERROR_R
65     *buf = '\0';
66     strerror_r(errno, buf, bufsz);
67     /* if buffer is unset - use strerror anyway (GLIBC bug) */
68     if (*buf == '\0')
69         strcpy(buf, strerror(yaz_errno()));
70 #else
71     strcpy(buf, strerror(yaz_errno()));
72 #endif
73 /* UNIX */
74 #endif
75     if ((cp = strrchr(buf, '\n')))
76         *cp = '\0';
77     if ((cp = strrchr(buf, '\r')))
78         *cp = '\0';
79 }
80 /*
81  * Local variables:
82  * c-basic-offset: 4
83  * c-file-style: "Stroustrup"
84  * indent-tabs-mode: nil
85  * End:
86  * vim: shiftwidth=4 tabstop=8 expandtab
87  */
88