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