Skip to content

Instantly share code, notes, and snippets.

@mattn
Created February 17, 2009 02:13
Show Gist options
  • Select an option

  • Save mattn/65533 to your computer and use it in GitHub Desktop.

Select an option

Save mattn/65533 to your computer and use it in GitHub Desktop.
#include <iconv.h>
#include <stdio.h>
#include <string.h>
void mb_to_uc_fallback(
const char* inbuf,
size_t inbufsize,
void (*write_replacement) (const unsigned int *buf, size_t buflen, void* callback_arg),
void* callback_arg,
void* data) {
printf("mb_to_uc_fallback\n");
}
void uc_to_mb_fallback(
unsigned int code,
void (*write_replacement) (const char *buf, size_t buflen, void* callback_arg),
void* callback_arg,
void* data) {
printf("uc_to_mb_fallback\n");
}
void mb_to_wc_fallback(
const char* inbuf, size_t inbufsize,
void (*write_replacement) (const wchar_t *buf, size_t buflen, void* callback_arg),
void* callback_arg,
void* data) {
printf("mb_to_wc_fallback\n");
}
void wc_to_mb_fallback(
wchar_t code,
void (*write_replacement) (const char *buf, size_t buflen, void* callback_arg),
void* callback_arg,
void* data) {
printf("wc_to_mb_fallback\n");
}
int code_convert(
const char *from_chrset,
const char *to_chrset,
const char *inbuf,
int in_len,
char *outbuf,
int out_len)
{
iconv_t cd;
struct iconv_fallbacks fallback = {
mb_to_uc_fallback,
uc_to_mb_fallback,
mb_to_wc_fallback,
wc_to_mb_fallback,
NULL // data
};
cd = iconv_open(to_chrset, from_chrset);
if (cd == 0) {
printf("can't open charset %s !\n", to_chrset);
return -1;
}
iconvctl(cd, ICONV_SET_FALLBACKS, &fallback);
memset(outbuf, 0, out_len);
if (iconv(cd, (char**)&inbuf, &in_len, &outbuf, &out_len ) == -1) {
fprintf(stderr, "%s\n", strerror(errno));
return -1;
}
iconv_close(cd);
return 0;
}
int main(void) {
// あいう~
const char* from = "\xe3\x81\x82\xe3\x81\x84\xe3\x81\x86\xef\xbd\x9e";
char to[256] = {0};
code_convert("utf-8", "char", from, strlen(from), to, sizeof(to));
printf("%s\n", to);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment