1 #include <errno.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <glib.h>
7 #include "config.h"
8 #include "support.h"
10 #ifdef HAVE_LOCALE_H
11 #include <locale.h>
12 #endif
14 #ifdef HAVE_ICONV
15 #include <iconv.h>
16 #endif
18 #ifdef HAVE_LANGINFO_CODESET
19 #include <langinfo.h>
20 #endif
22 #define BUFSIZE 1024
25 static char *charset = NULL;
27 #ifdef HAVE_LOCALE_H
28 static char *locale = NULL;
29 #endif
31 #ifdef HAVE_ICONV
32 iconv_t iconv_from_uft8 = (iconv_t)(-1);
33 iconv_t iconv_to_uft8 = (iconv_t)(-1);
34 #endif
37 #ifndef HAVE_LIBGEN_H
39 char *
40 remove_trailing_slash(char *path)
41 {
42 int len;
44 if( path==NULL )
45 return NULL;
47 len=strlen(path);
48 if( len>1 && path[len-1] == '/' )
49 path[len-1] = '\0';
51 return path;
52 }
55 char *
56 basename(char *path)
57 {
58 char *end;
60 path = remove_trailing_slash(path);
61 end = path + strlen(path);
63 while( end>path && *end!='/' )
64 end--;
66 if( *end=='/' && end!=path )
67 return end+1;
69 return path;
70 }
72 #endif /* HAVE_LIBGEN_H */
75 int
76 charset_init(void)
77 {
78 #ifdef HAVE_LOCALE_H
79 /* get current locale */
80 if( (locale=setlocale(LC_CTYPE,"")) == NULL )
81 {
82 fprintf(stderr,"setlocale() - failed!\n");
83 return -1;
84 }
85 #endif
87 #ifdef HAVE_LANGINFO_CODESET
88 /* get charset */
89 if( (charset=nl_langinfo(CODESET)) == NULL )
90 {
91 fprintf(stderr,
92 "nl_langinfo() failed using default:" DEFAULT_CHARSET "\n");
93 }
94 #endif
96 if( charset==NULL )
97 charset = DEFAULT_CHARSET;
99 #ifdef HAVE_ICONV
100 /* allocate descriptor for character set conversion */
101 iconv_from_uft8 = iconv_open(charset, "UTF-8");
102 if( iconv_from_uft8 == (iconv_t)(-1) )
103 {
104 perror("iconv_open");
105 return -1;
106 }
107 #endif
109 return 0;
110 }
112 int
113 charset_close(void)
114 {
115 #ifdef HAVE_ICONV
116 if( iconv_from_uft8 == (iconv_t)(-1) )
117 {
118 iconv_close(iconv_from_uft8);
119 iconv_from_uft8 = (iconv_t)(-1);
120 }
121 if( iconv_to_uft8 == (iconv_t)(-1) )
122 {
123 iconv_close(iconv_to_uft8);
124 iconv_to_uft8 = (iconv_t)(-1);
125 }
126 #endif
127 return 0;
128 }
132 char *
133 utf8_to_locale(char *str)
134 {
135 #ifdef HAVE_ICONV
136 size_t inleft;
137 size_t retlen;
138 char *ret;
140 if( iconv_from_uft8 == (iconv_t)(-1) )
141 return strdup(str);
143 ret = NULL;
144 retlen = 0;
145 inleft = strlen(str);
146 while( inleft>0 )
147 {
148 char buf[BUFSIZE];
149 size_t outleft = BUFSIZE;
150 char *bufp = buf;
152 if( iconv(iconv_from_uft8, &str, &inleft, &bufp, &outleft) <0 )
153 {
154 perror("iconv");
155 free(ret);
156 return NULL;
157 }
158 ret = realloc(ret, BUFSIZE-outleft+1);
159 memcpy(ret+retlen, buf, BUFSIZE-outleft);
160 retlen += BUFSIZE-outleft;
161 ret[retlen] = '\0';
162 }
163 return ret;
165 #else
166 return strdup(str);
167 #endif
168 }