Skip to content

Instantly share code, notes, and snippets.

@Witiko
Created November 4, 2013 10:23
Show Gist options
  • Select an option

  • Save Witiko/7300698 to your computer and use it in GitHub Desktop.

Select an option

Save Witiko/7300698 to your computer and use it in GitHub Desktop.
#include <unistd.h> /* STDIN_FILENO */
#include <locale.h> /* LC_ALL, setlocale() */
#include <langinfo.h> /* nl_langinfo(), CODESET */
#include <wchar.h> /* wchar_t, putwchar() */
#include <iconv.h> /* iconv_t, iconv_open(), iconv(), iconv_close() */
#include <stdlib.h> /* malloc(), EXIT_SUCCESS */
int main(void) {
setlocale(LC_ALL, ""); // We initialize the locale
iconv_t converter = iconv_open("WCHAR_T", nl_langinfo(CODESET)); // We initialize a converter
wchar_t out; // We allocate memory for one wide char on stack
char* pOut = (char*)&out; // We allocate memory for one wide char on stack
size_t outLeft = sizeof(wchar_t);
while(outLeft > 0) { // Until we've read one wide char...
char in; // We allocate memory for one byte on stack
char* pIn=&in;
size_t inLeft = 1;
if(read(STDIN_FILENO, pIn, 1) == 0) break; // We read one byte from stdin to the buffer
iconv(converter, &pIn, &inLeft, &pOut, &outLeft); // We feed the byte to the converter
}
iconv_close(converter); // We deinitialize a converter
wprintf(L"%c\n", out); // We echo the wide char back to stdout
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment