加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

调用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] = ;
        int bufferSize = MultiByteToWideChar(CP_UTF8,utf8Text,NULL,0);
        WCHAR *unicodeString = (WCHAR *)malloc(sizeof(WCHAR) * bufferSize);
        MultiByteToWideChar(CP_UTF8,bufferSize);
        bufferSize = WideCharToMultiByte(CP_ACP,NULL);
        CHAR *gbkString = (CHAR *)malloc(sizeof(CHAR) * bufferSize);
        WideCharToMultiByte(CP_ACP,gbkString,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: %sn",outputFilename);
        }
        else
        {
            printf("Cannot write file: %sn",outputFilename);
        }
        free(gbkString);
        free(unicodeString);
        fclose(inputFile);
    }
    else
    {
        printf("Cannot read file: %sn",inputFilename);
    }
    system("pause");
    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读