1 /* Recode strings between character sets, using iconv.
2 Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public License as
6 published by the Free Software Foundation; either version 2.1, or (at
7 your option) any later version.
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 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public License along
15 with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
48 /* Convert a zero-terminated string STR from the FROM_CODSET code set
49 to the TO_CODESET code set. The returned string is allocated using
50 malloc, and must be dellocated by the caller using free. On
51 failure, NULL is returned and errno holds the error reason. Note
52 that if TO_CODESET uses \0 for anything but to terminate the
53 string, the caller of this function may have difficulties finding
54 out the length of the output string. */
56 iconv_string (const char *str, const char *from_codeset,
57 const char *to_codeset)
63 char *p = (char *) str;
64 size_t inbytes_remaining = strlen (p);
65 /* Guess the maximum length the output string can have. */
66 size_t outbuf_size = (inbytes_remaining + 1) * MB_LEN_MAX;
67 size_t outbytes_remaining = outbuf_size - 1; /* -1 for NUL */
72 if (strcmp (to_codeset, from_codeset) == 0)
76 cd = iconv_open (to_codeset, from_codeset);
77 if (cd == (iconv_t) -1)
80 outp = dest = (char *) malloc (outbuf_size);
85 err = iconv (cd, &p, &inbytes_remaining, &outp, &outbytes_remaining);
87 if (err == (size_t) - 1)
92 /* Incomplete text, do not report an error */
97 size_t used = outp - dest;
98 size_t newsize = outbuf_size * 2;
101 if (newsize <= outbuf_size)
107 newdest = (char *) realloc (dest, newsize);
114 outbuf_size = newsize;
117 outbytes_remaining = outbuf_size - used - 1; /* -1 for NUL */
137 int save_errno = errno;
139 if (iconv_close (cd) < 0 && !have_error)
141 /* If we didn't have a real error before, make sure we restore
142 the iconv_close error below. */
147 if (have_error && dest)