GBK转UTF-8示例
GbkToUtf8.cpp
#include <Windows.h> #include <iostream> #include <string> #include <fstream> int main() { using namespace std; string multiByteString = "我25岁。 I'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, multiByteString.c_str(), -1, unicodeString, bufferSize); bufferSize = WideCharToMultiByte(CP_UTF8, 0, unicodeString, -1, nullptr, 0, nullptr, nullptr); CHAR *utf8String = new CHAR[bufferSize]; WideCharToMultiByte(CP_UTF8, 0, unicodeString, -1, utf8String, bufferSize, nullptr, 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] = '