-3

I have multiple .txt files with the encoding format ANSI in a folder named folder1. I need convert it all to UTF-8 encoding type files in another empty folder with the name folder2. I don't want to convert the files one by one - I want to convert them all at a time.

  • At least tell us the language or operating system you want to do this on...?! – deceze Jun 27 '14 at 12:35
  • This [topic][1] will help you to solve your issue. [1]: http://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets – Perfect28 Jun 27 '14 at 12:38

1 Answers1

0

use MultiByteToWideChar() with CP_ACP to convert data to WideChar and then use WideCharToMultiByte() with CP_UTF8 to convert in utf8 if we are talking about 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;
    }

Above code converts single ANSI file to UTF8 , you can use CP_UTF16 any you want , Hope code will helpfull

Dipak
  • 672
  • 3
  • 9
  • 26