【问题标题】:How to convert encoding type of multiple .txt & .pro files from ANSI to UTF-8如何将多个 .txt 和 .pro 文件的编码类型从 ANSI 转换为 UTF-8
【发布时间】:2014-08-18 13:44:30
【问题描述】:

我在名为folder1 的文件夹中有多个编码格式为ANSI 的.txt 文件。我需要将其全部转换为另一个名为folder2 的空文件夹中的UTF-8 编码类型文件。 我不想一个一个地转换文件 - 我想一次转换所有文件。

【问题讨论】:

标签: encoding utf-8 character-encoding type-conversion


【解决方案1】:

使用 MultiByteToWideChar() 和 CP_ACP 将数据转换为 WideChar,然后使用 WideCharToMultiByte() 和 CP_UTF8 在 utf8 中转换(如果我们在谈论 c++)

static int to_utf8EncodeFile(std::wstring filePath)
{
    int error_code = 0;
    //read text file which will be in ANSI encoding type
    std::string fileName(filePath.begin(), filePath.end());
    std::string fileContent;
    fileContent = readFile(fileName.c_str());
    if(fileContent.empty())
    {
        return GetLastError();
    }
    int wchars_num =  MultiByteToWideChar( CP_ACP , 0 , fileContent.c_str() , -1, NULL , 0 );
    wchar_t* wstr = new wchar_t[wchars_num];
    error_code = MultiByteToWideChar( CP_ACP , 0 , fileContent.c_str() , -1, wstr , wchars_num );
    if(error_code == 0)
    {
        delete [] wstr;
        return GetLastError();
    }

    int size_needed = WideCharToMultiByte(CP_UTF8 , 0, &wstr[0], -1, NULL, 0, NULL, NULL);
    std::string strTo( size_needed, 0 );
    error_code = WideCharToMultiByte(CP_UTF8 , 0, &wstr[0], -1 , &strTo[0], size_needed, NULL, NULL);
    delete [] wstr;
    if(error_code == 0)
    {
        return GetLastError();
    }

    //Write utf-8 file
    std::ofstream utf_stream(filePath.c_str()); 
    utf_stream << strTo.c_str();
    utf_stream.close();
    return error_code;
    }

以上代码将单个 ANSI 文件转换为 UTF8,你可以使用任何你想要的 CP_UTF16, 希望代码会有所帮助

【讨论】:

    猜你喜欢
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 2020-10-11
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多