我的程序的这一部分试图重命名所有文件夹和子文件夹。所有其他功能都在另一个代码中,这里我只是通过提供一个路径来重命名一个文件夹。
因为重命名似乎不适合我,所以我尝试使用MoveFile。
我知道它需要一个LPCTSTR值。但是,我目前提供的路径(来自std::filesystem::directory_entry -> std::->::path)->LPCTSTR不被接受。
我明白,我没有正确地转换它,我可能必须在变量前面提供一个"L“,但是我找不到语法,也找不出语法。

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)));
}发布于 2022-08-02 07:17:25
不能直接向字符指针键入强制转换std::filesystem::path对象。这正是错误信息告诉您的。而且您不能对变量使用L前缀,只能使用编译时文本。
您需要调用path::c_str()方法,例如:
MoveFileW(std::filesystem::path(dirEntry).c_str(), std::filesystem::path(path_string).c_str());或者,调用path::(w)string()方法,然后对返回的std::(w)string对象调用c_str(),例如:
MoveFileW(std::filesystem::path(dirEntry).wstring().c_str(), std::filesystem::path(path_string).wstring().c_str());尽管如此,std::rename()很可能是在Windows上使用MoveFile/Ex()内部实现的,所以这是一种可能的XY Problem。std::rename()是首选的解决方案,所以您应该集中精力找出为什么它不适合您。
更新:
另外,您所展示的代码重复使用了不必要的临时std::filesystem::path对象。试着简化代码,如下所示:
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());
}
}https://stackoverflow.com/questions/73203313
复制相似问题