首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MoveFile函数转换语法/如何使用MoveFile与变量一起重命名文件夹

MoveFile函数转换语法/如何使用MoveFile与变量一起重命名文件夹
EN

Stack Overflow用户
提问于 2022-08-02 07:08:08
回答 1查看 72关注 0票数 -2

我的程序的这一部分试图重命名所有文件夹和子文件夹。所有其他功能都在另一个代码中,这里我只是通过提供一个路径来重命名一个文件夹。

因为重命名似乎不适合我,所以我尝试使用MoveFile。

我知道它需要一个LPCTSTR值。但是,我目前提供的路径(来自std::filesystem::directory_entry -> std::->::path)->LPCTSTR不被接受。

我明白,我没有正确地转换它,我可能必须在变量前面提供一个"L“,但是我找不到语法,也找不出语法。

代码语言:javascript
复制
bool renameFolder(std::string confirmStr3, auto dirEntry, std::string& replacedStr, std::string& insertStr, int& foldername_replacements)
{
    std::string path_string = dirEntry.path().string();

    path_string = std::filesystem::path(path_string).filename().string();

    replace_all(path_string, replacedStr, insertStr);

    path_string = getFolderPath(std::filesystem::path(dirEntry).string()) + "\\" + path_string;
 

    if (std::filesystem::path(dirEntry) != std::filesystem::path(path_string))
        foldername_replacements++;


    //std::filesystem::rename(std::filesystem::path(dirEntry), std::filesystem::path(path_string));
    MoveFile(LPCTSTR(std::filesystem::path(dirEntry)), LPCTSTR(std::filesystem::path(path_string)));

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-02 07:17:25

不能直接向字符指针键入强制转换std::filesystem::path对象。这正是错误信息告诉您的。而且您不能对变量使用L前缀,只能使用编译时文本。

您需要调用path::c_str()方法,例如:

代码语言:javascript
复制
MoveFileW(std::filesystem::path(dirEntry).c_str(), std::filesystem::path(path_string).c_str());

或者,调用path::(w)string()方法,然后对返回的std::(w)string对象调用c_str(),例如:

代码语言:javascript
复制
MoveFileW(std::filesystem::path(dirEntry).wstring().c_str(), std::filesystem::path(path_string).wstring().c_str());

尽管如此,std::rename()很可能是在Windows上使用MoveFile/Ex()内部实现的,所以这是一种可能的XY Problemstd::rename()是首选的解决方案,所以您应该集中精力找出为什么它不适合您。

更新:

另外,您所展示的代码重复使用了不必要的临时std::filesystem::path对象。试着简化代码,如下所示:

代码语言:javascript
复制
bool renameFolder(std::string confirmStr3, auto dirEntry, std::string& replacedStr, std::string& insertStr, int& foldername_replacements)
{
    auto dirEntryPath = dirEntry.path();
    auto file_name = dirEntryPath.filename().string();

    replace_all(file_name, replacedStr, insertStr);

    auto newDirEntryPath = dirEntryPath / file_name;    
    if (dirEntryPath != newDirEntryPath)
    {
        ++foldername_replacements;

        //std::filesystem::rename(dirEntryPath, newDirEntryPath);
        MoveFileW(dirEntryPath.c_str(), newDirEntryPath.c_str());
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73203313

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档