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