Encoding 如何转换多个.txt&;的编码类型。从ANSI到UTF-8的pro文件

Encoding 如何转换多个.txt&;的编码类型。从ANSI到UTF-8的pro文件,encoding,utf-8,character-encoding,type-conversion,Encoding,Utf 8,Character Encoding,Type Conversion,我在名为folder1的文件夹中有多个编码格式为ANSI的.txt文件。我需要将其全部转换为另一个名为folder2的空文件夹中的UTF-8编码类型文件。 我不想一个接一个地转换文件-我想一次转换所有文件。使用带CP_ACP的MultiByteToWideChar()将数据转换为WideChar,然后使用带CP_UTF8的WideCharToMultiByte()将数据转换为UTF8(如果我们讨论的是c)++ static int to_utf8EncodeFile(std::wstring f

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

使用带CP_ACP的MultiByteToWideChar()将数据转换为WideChar,然后使用带CP_UTF8的WideCharToMultiByte()将数据转换为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;
    }
static int to_utf8EncodeFile(std::wstring filePath)
{
int error_code=0;
//读取ANSI编码类型的文本文件
字符串文件名(filePath.begin(),filePath.end());
std::字符串文件内容;
fileContent=readFile(fileName.c_str());
if(fileContent.empty())
{
返回GetLastError();
}
int wchars_num=MultiByteToWideChar(CP_ACP,0,fileContent.c_str(),-1,NULL,0);
wchar_t*wstr=新的wchar_t[wchars_num];
error_code=MultiByteToWideChar(CP_ACP,0,fileContent.c_str(),-1,wstr,wchars_num);
如果(错误代码==0)
{
删除[]wstr;
返回GetLastError();
}
int size_needed=WideCharToMultiByte(CP_UTF8,0,&wstr[0],-1,NULL,0,NULL,NULL);
std::字符串strTo(需要的大小为0);
错误代码=宽图表多字节(CP\U UTF8,0,&wstr[0],-1,&strTo[0],需要大小,NULL,NULL);
删除[]wstr;
如果(错误代码==0)
{
返回GetLastError();
}
//写入utf-8文件
std::of流utf_流(filePath.c_str());

utf_stream至少告诉我们您希望在哪种语言或操作系统上执行此操作…?!此[主题][1]将帮助您解决问题。[1]: