读写中文路径下文件的通用方案

编程环境全部设置为utf8

h、cpp文件全部以utf8 unicode(utf8带签名,代码页65001)格式保存。

qt5以上程序在main函数中设置:

QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

配置文件、xml文件等都采用utf8格式存储。
数据库、网络数据,均采用utf8编码。

底层代码封装utf8到local的转换

win7默认字符集是local。gb2312之类的。
win10默认字符集似乎也不是utf8。
那么,当底层读写文件时,发现读写失败,可以继续执行以下代码:
1、判断file_name是否为utf8字符集,如果是,转化为本地字符集继续读写。
2、如果不是utf8字符集,那就直接报错退出。

对于上层代码的编写人员来说,不需要关心文件名的转码问题(但是要求全部环境都默认utf8)。
以下是示例代码,用pugixml开源库读写xml文件,底层封装编码问题后,上层就省事了。

    pugi::xml_document xml_doc;
    pugi::xml_parse_result result = xml_doc.load_file(file_name.c_str());
    int flag = result.status;
    if (flag != pugi::status_ok)
    {
        if (isUtf8Str(file_name))
        {
            const std::string local_file_name = CodePageInfor::Utf8ToLocal(file_name);
            result = xml_doc.load_file(local_file_name.c_str());
            flag = result.status;
        }
    }
    if (flag == pugi::status_ok){
    ...
    }
    else{
    ...
    }
    pugi::xml_document save_xml_doc;
    pugi::xml_node node = save_xml_doc.prepend_child(pugi::node_declaration);
    node.append_attribute("version") = "1.0";
    node.append_attribute("encoding") = encoding.c_str();
    pugi::xml_node root = save_xml_doc.append_child(p_root_ref->tag_name().c_str());
    int flag = write_to_xml(root, p_root_ref);
    if (flag != pugi::status_ok)
    {
        show_pugi_error(flag, file_name);
    }
    bool b = save_xml_doc.save_file(file_name.c_str(), PUGIXML_TEXT("\t"));
    if (!b)
    {
        if (isUtf8Str(file_name))
        {
            const std::string local_file_name = CodePageInfor::Utf8ToLocal(file_name);
            b = save_xml_doc.save_file(local_file_name.c_str(), PUGIXML_TEXT("\t"));
        }
        if (!b)
        {
            GuiLogFL(std::string("pugi::xml_document.save_file(...) error:") + file_name);
        }
    }

iconv库及cpp接口封装:
https://download.csdn.net/download/weixin_43172531/12073477
CodePageInfor类的定义:
https://blog.csdn.net/weixin_43172531/article/details/103424465
isUtf8Str的定义:
https://blog.csdn.net/weixin_43172531/article/details/103800672

猜你喜欢

转载自blog.csdn.net/weixin_43172531/article/details/103801019
今日推荐