我需要创建一个函数来删除诸如“..”或“.”之类的任何内容在文件路径中。所以如果我做
resolvePath("/root\\\\directory1/directory2\\\\\\\\..")
它会返回"root/directory1
。我尝试为路径的每一部分制作一个 char* 数组,但我无法获取它的每一段。
两个真正跨平台的选择是 boost 和 Qt,所以这里展示了两个:
path canonical(const path& p, const path& base = current_path());
path canonical(const path& p, system::error_code& ec);
path canonical(const path& p, const path& base, system::error_code& ec);
QFileInfo fileInfo("/root\\\\directory1/directory2\\\\\\\\.."))
qDebug() << fileInfo.canonicalFilePath();
从您提供的示例路径来看,您使用的是类 Unix 系统。然后,您可以使用
realpath()
规范化您的路径。这至少存在于 Linux、BSD 和 Mac OS 上。
标准库 (C++17) 现在提供了一个可行的解决方案:
#include <iostream>
#include <filesystem>
int main()
{
// resolves based on current dir
std::filesystem::path mypath = std::filesystem::canonical("../dir/file.ext");
std::cout << mypath.generic_string(); // root/parent_dir/dir/file.ext
return 0;
}
文档: