c++ convert file to utf-8

要将文件从其它编码格式(如 ANSI 或 UTF-16)转换为 UTF-8 编码,可以使用 C++ 中的一些函数来实现。以下是一个简单的示例:

#include <iostream>
#include <fstream>
#include <string>
int main() {
    // 打开文件
    std::ifstream infile("input.txt", std::ios::binary);
    if (!infile.is_open()) {
        std::cerr << "Error opening file\n";
        return 1;
    // 读取文件内容
    std::string content((std::istreambuf_iterator<char>(infile)), std::istreambuf_iterator<char>());
    infile.close();
    // 将内容转换为 UTF-8 编码
    std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
    std::string utf8content = converter.to_bytes(std::wstring(content.begin(), content.end()));
    // 写入新文件
    std::ofstream outfile("output.txt", std::ios::binary);
    if (!outfile.is_open()) {
        std::cerr << "Error creating file\n";
        return 1;
    outfile.write(utf8content.c_str(), utf8content.size());
    outfile.close();
    std::cout << "Conversion successful!\n";
    return 0;

这个示例程序打开了一个名为 "input.txt" 的文件,并将其内容读取到一个 std::string 对象中。然后,使用 std::wstring_convert<> 类型和 std::codecvt_utf8<wchar_t> 模板将字符串从其它编码格式(如 ANSI 或 UTF-16)转换为 UTF-8 编码。最后,将转换后的内容写入名为 "output.txt" 的新文件中。

注意,这个示例程序使用二进制模式打开文件。这是因为在 ANSI 编码中,一些字符可能包含 null 终止符,而在二进制模式下,这些字符不会被解释为文件结束符。

希望这个示例程序可以帮助您将文件从其它编码格式转换为 UTF-8 编码。

  •