今天写C++程序的时候,因为失误,创建了一个以 “.” 为最后一个字符的文件夹。
试图删除的时候,提示找不到该项目,也无法重命名
我查阅互联网许久也没找到解决方案,但是逐渐确定了是因为文件夹的结尾是"."
找到原因之后,我觉得解铃还须系铃人,还是使用C++来编写程序解决问题吧。于是有了这段代码。
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
void remove_trailing_dot_from_files()
{
std::string path = "./"; // 指定要遍历的目录路径(当前目录)
try
{
// 遍历目录中的所有条目
for (const auto &entry : fs::directory_iterator(path))
{
std::string oldName = entry.path().filename().string();
// 检查文件名是否以点结尾且不为空
if (!oldName.empty() && oldName.back() == '.')
{
// 构造新文件名(移除最后一个字符)
std::string newName = oldName.substr(0, oldName.size() - 1);
fs::path newPath = entry.path().parent_path() / newName;
// 执行重命名操作
fs::rename(entry.path(), newPath);
std::cout << "重命名: " << oldName << " -> " << newName << std::endl;
}
else
{
std::cout << "无需修改: " << oldName << std::endl;
}
}
}
catch (const fs::filesystem_error &e)
{
std::cerr << "错误: " << e.what() << std::endl;
}
}
int main()
{
remove_trailing_dot_from_files();
return 0;
}
放到 test.
所在文件夹后编译运行即可
顺利解决问题,开心~(虽然花了很久。