使用C ++中的SHIFT-JIS编码保存文件 [英] Save file using SHIFT-JIS encoding in C++
本文介绍了使用C ++中的SHIFT-JIS编码保存文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了一个程序来读取文件。文件编码为UTF-8,文件内容为日语。我用'wstring'来存储文件的行。现在我想使用SHIFT-JIS编码保存文件。如何使用C ++执行此操作?
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++?
推荐答案
将文件读入缓冲区,使用 MultiByteToWideChar()$将文本转换为Unicode c $ c>,使用 WideCharToMultiByte()
将其转换为SHIFT-JIS,并将其写入JIS文件:
Read the file into a buffer, convert the text to Unicode usingMultiByteToWideChar()
, convert it to SHIFT-JIS usingWideCharToMultiByte()
, and write that to the JIS file:
#include <io.h>
void Utf8FileToJis(LPCTSTR lpszUtf8File, LPCTSTR lpszJisFile)
{
FILE *fUtf8File = _tfopen(lpszUtf8File, _T("rb"));
if (NULL == fUtf8File)
return;
FILE *fJisFile = _tfopen(lpszJisFile, _T("wb"));
if (NULL == fJisFile)
{
fclose(fUtf8File);
return;
}
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 msdn.microsoft.com/en-us/library/dd317756%28v=vs.85%29.aspx
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;
fclose(fJisFile);
fclose(fUtf8File);
}
这篇关于使用C ++中的SHIFT-JIS编码保存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文