Click here to Skip to main content
14,869,890 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have written a program to read from a file. The file encoding is UTF-8 and content of the file is Japanese language. I have used 'wstring' to store the lines of the file. Now I want to save the file using SHIFT-JIS encoding. How can I do this using C++?

1 solution

Read the file into a buffer, convert the text to Unicode using MultiByteToWideChar(), convert it to SHIFT-JIS using WideCharToMultiByte(), and write that to the JIS file:

[EDIT: Added code to read and write files]
#include <io.h>

void Utf8FileToJis(LPCTSTR lpszUtf8File, LPCTSTR lpszJisFile)
    FILE *fUtf8File = _tfopen(lpszUtf8File, _T("rb"));
    if (NULL == fUtf8File)
    FILE *fJisFile = _tfopen(lpszJisFile, _T("wb"));
    if (NULL == fJisFile)
    int nLen = _filelength(fileno(fUtf8File));
    LPSTR lpszBuf = new char[nLen];
    fread(lpszBuf, 1, nLen, fUtf8File);
    int nWideLen = ::MultiByteToWideChar(CP_UTF8, 0, lpszBuf, nLen, NULL, 0);
    LPWSTR lpszWide = new WCHAR[nWideLen];
    ::MultiByteToWideChar(CP_UTF8, 0, lpszBuf, nLen, lpszWide, nWideLen);

    // SHIFT-JIS has code page number 932
    // see
    int nJisLen = ::WideCharToMultiByte(932, 0, lpszWide, nWideLen, NULL, 0, NULL, NULL);
    LPSTR lpszJis = new char[nJisLen];
    ::WideCharToMultiByte(932, 0, lpszWide, nWideLen, lpszJis, nJisLen, NULL, NULL);

    fwrite(lpszJis, 1 , nJisLen, fJisFile);

    delete [] lpszJis;
    delete [] lpszWide;
    delete [] lpszBuf;
JakirBB 13-Jul-13 15:54pm
Can you please provide me a full code with reading from and writing to a file? I'll be very grateful to you. Thanks in advance.
Jochen Arndt 14-Jul-13 5:15am
I have updated my solution. Reading and writing files is a basic task that can be done using various methods (I decided to use the C Standard library functions).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900