String conversion with different charsets
[infodrom/newmail] / charset.c
1 /*
2     Copyright (c) 2006  Joey Schulze <joey@infodrom.org>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18
19 #include <locale.h>
20 #include <langinfo.h>
21 #include <string.h>
22 #include <iconv.h>
23
24 char *charset = NULL;
25
26 /*
27  * Determine the output character set
28  */
29 void set_charset()
30 {
31   setlocale (LC_CTYPE, "");
32
33   charset = strdup (nl_langinfo(CODESET));
34 }
35
36 /*
37  * Convert a word from an arbitrary charset into the output character set
38  *
39  * No conversion is performed when both charsets are equal
40  */
41 char *convert_word(const char *encoding, char *inbuf, char *outbuf, size_t outbytesleft)
42 {
43   iconv_t cd;
44   char *inptr, *outptr;
45   size_t inbytesleft;
46   size_t nconv;
47
48   if (!charset || !strcasecmp (encoding, charset)) {
49     memmove (outbuf, inbuf, strlen(inbuf)<outbytesleft?strlen(inbuf)+1:strlen(inbuf));
50     outbuf[outbytesleft-1] = '\0';
51     return outbuf;
52   }
53
54   cd = iconv_open (charset, encoding);
55
56   inbytesleft = strlen (inbuf)+1;
57   inptr = inbuf;
58   outptr = outbuf;
59
60   nconv = iconv (cd, &inptr, &inbytesleft, &outptr, &outbytesleft);
61   iconv_close(cd);
62
63   return outbuf;
64 }
65
66
67 /*
68  * Needs to be called with LANG=de_DE.ISO-8859-1
69
70 void test_charset()
71 {
72   char outbuf[100];
73   size_t size = 99;
74
75   memset (outbuf, 0, sizeof (outbuf));
76   printf ("%s\n", convert_word ("UTF-8", "für ein", outbuf, size));
77   printf ("%s\n", outbuf);
78   if (!strcmp(outbuf, "für ein"))
79     printf ("charset.c: test passed\n");
80   else
81     printf ("charset.c: test failed\n");
82 }
83
84 */