d2dc9759c7e173f94a0535dce9dd96807e2efd5e
1 #include <errno.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <glib.h>
7 #include "config.h"
9 #ifdef HAVE_LOCALE_H
10 #ifdef HAVE_LANGINFO_H
11 #ifdef HAVE_ICONV
12 #include <locale.h>
13 #include <langinfo.h>
14 #include <iconv.h>
15 #define ENABLE_CHARACTER_SET_CONVERSION
16 #endif
17 #endif
18 #endif
20 #include "support.h"
22 #define BUFSIZE 1024
24 #ifdef ENABLE_CHARACTER_SET_CONVERSION
25 static char *locale = NULL;
26 static char *charset = NULL;
27 iconv_t iconv_from_uft8 = (iconv_t)(-1);
28 iconv_t iconv_to_uft8 = (iconv_t)(-1);
29 #endif
33 #ifndef HAVE_LIBGEN_H
35 char *
36 remove_trailing_slash(char *path)
37 {
38 int len;
40 if( path==NULL )
41 return NULL;
43 len=strlen(path);
44 if( len>1 && path[len-1] == '/' )
45 path[len-1] = '\0';
47 return path;
48 }
51 char *
52 basename(char *path)
53 {
54 char *end;
56 path = remove_trailing_slash(path);
57 end = path + strlen(path);
59 while( end>path && *end!='/' )
60 end--;
62 if( *end=='/' && end!=path )
63 return end+1;
65 return path;
66 }
68 #endif /* HAVE_LIBGEN_H */
71 int
72 charset_init(void)
73 {
74 #ifdef ENABLE_CHARACTER_SET_CONVERSION
75 /* get current locale */
76 if( (locale=setlocale(LC_CTYPE,"")) == NULL )
77 {
78 fprintf(stderr,"setlocale() - failed!\n");
79 return -1;
80 }
82 /* get charset */
83 if( (charset=nl_langinfo(CODESET)) == NULL )
84 {
85 fprintf(stderr,"nl_langinfo() - failed!\n");
86 return -1;
87 }
89 /* allocate descriptor for character set conversion */
90 iconv_from_uft8 = iconv_open(charset, "UTF-8");
91 if( iconv_from_uft8 == (iconv_t)(-1) )
92 {
93 perror("iconv_open");
94 return -1;
95 }
96 #endif
98 return 0;
99 }
101 int
102 charset_close(void)
103 {
104 #ifdef ENABLE_CHARACTER_SET_CONVERSION
105 if( iconv_from_uft8 == (iconv_t)(-1) )
106 {
107 iconv_close(iconv_from_uft8);
108 iconv_from_uft8 = (iconv_t)(-1);
109 }
110 if( iconv_to_uft8 == (iconv_t)(-1) )
111 {
112 iconv_close(iconv_to_uft8);
113 iconv_to_uft8 = (iconv_t)(-1);
114 }
115 #endif
116 return 0;
117 }
121 char *
122 utf8_to_locale(char *str)
123 {
124 #ifdef ENABLE_CHARACTER_SET_CONVERSION
125 size_t inleft;
126 size_t retlen;
127 char *ret;
129 if( iconv_from_uft8 == (iconv_t)(-1) )
130 return strdup(str);
132 ret = NULL;
133 retlen = 0;
134 inleft = strlen(str);
135 while( inleft>0 )
136 {
137 char buf[BUFSIZE];
138 size_t outleft = BUFSIZE;
139 char *bufp = buf;
141 if( iconv(iconv_from_uft8, &str, &inleft, &bufp, &outleft) <0 )
142 {
143 perror("iconv");
144 free(ret);
145 return NULL;
146 }
147 ret = realloc(ret, BUFSIZE-outleft+1);
148 memcpy(ret+retlen, buf, BUFSIZE-outleft);
149 retlen += BUFSIZE-outleft;
150 ret[retlen] = '\0';
151 }
152 return ret;
154 #else
155 return strdup(str);
156 #endif
157 }