系统相关
首页 > 系统相关> > 调用Windows API实现GBK和UTF-8的相互转换

调用Windows API实现GBK和UTF-8的相互转换

作者:互联网

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, 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] = '\0';
        int bufferSize = MultiByteToWideChar(CP_UTF8, 0, utf8Text, -1, NULL, 0);
        WCHAR *unicodeString = (WCHAR *)malloc(sizeof(WCHAR) * bufferSize);
        MultiByteToWideChar(CP_UTF8, 0, utf8Text, -1, unicodeString, bufferSize);
        bufferSize = WideCharToMultiByte(CP_ACP, 0, unicodeString, -1, NULL, 0, NULL, NULL);
        CHAR *gbkString = (CHAR *)malloc(sizeof(CHAR) * bufferSize);
        WideCharToMultiByte(CP_ACP, 0, unicodeString, -1, gbkString, bufferSize, NULL, NULL);
        const char *outputFilename = "GbkText.txt";
        FILE *outputFile = fopen(outputFilename, "w");
        if (outputFile)
        {
            fwrite(gbkString, sizeof(CHAR), bufferSize - 1, outputFile);
            fclose(outputFile);
            printf("The GBK text has been written to file: %s\n", outputFilename);
        }
        else
        {
            printf("Cannot write file: %s\n", outputFilename);
        }
        free(gbkString);
        free(unicodeString);
        fclose(inputFile);
    }
    else
    {
        printf("Cannot read file: %s\n", inputFilename);
    }
    system("pause");
    return 0;
}

 

标签:bufferSize,UTF,Windows,NULL,GBK,CHAR,include,CP,unicodeString
来源: https://www.cnblogs.com/buyishi/p/10396919.html