c ++重命名文件名其他语言

问题描述 投票:-1回答:1

我想重命名某些文件,

某些文件的名称是俄语,中文和德语

该程序只能修改名称为英语的文件。

是什么问题?请指导我

std::wstring ToUtf16(std::string str)
{
    std::wstring ret;
    int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), NULL, 0);
    if (len > 0)
    {
        ret.resize(len);
        MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), &ret[0], len);
    }
    return ret;
}
int main()
{
    const std::filesystem::directory_options options = (
        std::filesystem::directory_options::follow_directory_symlink |
        std::filesystem::directory_options::skip_permission_denied
        );
    try
    {
        for (const auto& dirEntry :
            std::filesystem::recursive_directory_iterator("C:\\folder",
                std::filesystem::directory_options(options)))
        {
            filesystem::path  myfile(dirEntry.path().u8string());
            string uft8path1 = dirEntry.path().u8string();
            string uft8path3 = myfile.parent_path().u8string() + "/" + myfile.filename().u8string();
            _wrename(
                ToUtf16(uft8path1).c_str()
                ,
                ToUtf16(uft8path3).c_str()
            );
            std::cout << dirEntry.path().u8string() << std::endl;
        }
    }
    catch (std::filesystem::filesystem_error & fse)
    {
        std::cout << fse.what() << std::endl;
    }
    system("pause");
}

enter image description here

c++ unicode file-rename
1个回答
0
投票
filesystem::path  myfile(dirEntry.path().u8string());

Windows支持UTF16和ANSI,不支持API的UTF8(无论如何都不是标准的)。提供UTF8字符串时,它认为存在ANSI输入。使用wstring()表示UTF16:

filesystem::path  myfile(dirEntry.path().wstring());

或只放:

filesystem::path  myfile(dirEntry);

同样,将wstring()用于其他对象。

wstring path1 = dirEntry.path();
wstring path3 = myfile.parent_path().wstring() + L"/" + myfile.filename().wstring();
_wrename(path1.c_str(), path3.c_str());

重命名文件将在您输入UTF16时正常工作。但是控制台有限的Unicode支持还有另一个问题。您不能打印一些带有字体更改的亚洲字符。使用调试器或MessageBoxW查看亚洲字符。

使用_setmodewcout打印UTF16。

也请注意,std::filesystem支持/运算符以添加路径。示例:

#include <io.h> //for _setmode
#include <fcntl.h> 
...

int main()
{
    _setmode(_fileno(stdout), _O_U16TEXT);

    const std::filesystem::directory_options options = (
        std::filesystem::directory_options::follow_directory_symlink |
        std::filesystem::directory_options::skip_permission_denied
        );
    try
    {
        for(const auto& dirEntry :
            std::filesystem::recursive_directory_iterator(L"C:\\folder",
                std::filesystem::directory_options(options)))
        {
            filesystem::path  myfile(dirEntry);
            auto path1 = dirEntry;
            auto path3 = myfile.parent_path() / myfile;
            std::wcout << path1 << ", " << path3 << endl;
            //filesystem::rename(path1, path3);
        }
    }
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.