调用Windows API实现GBK和UTF-8的相互转换
发布时间:2020-12-14 02:32:27 所属栏目:Windows 来源:网络整理
导读:GBK转UTF-8示例 GbkToUtf8.cpp #include Windows.h #include iostream #include string #include fstream int main(){ using namespace std; string multiByteString = " 我25岁。nI‘m 25 years old. " ; int bufferSize = MultiByteToWideChar(CP_ACP, 0
GBK转UTF-8示例 GbkToUtf8.cpp #include <Windows.h> #include <iostream> #include <string> #include <fstream> int main() { using namespace std; string multiByteString = "我25岁。nI‘m 25 years old."; int bufferSize = MultiByteToWideChar(CP_ACP,0,multiByteString.c_str(),-1,nullptr,0); WCHAR *unicodeString = new WCHAR[bufferSize]; MultiByteToWideChar(CP_ACP,0,-1,unicodeString,bufferSize); bufferSize = WideCharToMultiByte(CP_UTF8,0,nullptr); CHAR *utf8String = new CHAR[bufferSize]; WideCharToMultiByte(CP_UTF8,utf8String,bufferSize,nullptr); ofstream ofs("UTF8.txt"); if (ofs) { ofs.write(utf8String,bufferSize - 1); cout << "A UTF-8 string has been written to file: UTF8.txt" << endl; } else { cout << "Cannot create file: UTF8.txt" << endl; } delete[] utf8String; delete[] unicodeString; system("pause"); return 0; } UTF-8转GBK示例 Utf8ToGbk.c #include <Windows.h> #include <stdio.h> #define BUFFER_SIZE 1000 int main() { const char *inputFilename = "Utf8Text.txt"; FILE *inputFile = fopen(inputFilename,"r"); if (inputFile) { char utf8Text[BUFFER_SIZE]; size_t numberOfObjectsRead = fread(utf8Text,sizeof(char),BUFFER_SIZE,inputFile); utf8Text[numberOfObjectsRead] = ‘ |