如何解析文件路径
How to resolve a file path
我需要创建一个函数来删除诸如".."之类的任何内容或"."在文件路径中。所以如果我做了resolvePath("/root\\directory1/directory2\\\\..")
,它会返回"root/directory1
。我试着为路径的每一部分制作一个char*数组,但我无法获得它的每一段。
两种真正的跨平台替代方案是boost和Qt,因此下面将展示这两种方案:
Boost解决方案:Boost::filesystem::canonical
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);
Qt解决方案:QFileInfo
QFileInfo fileInfo("/root\\directory1/directory2\\\\.."))
qDebug() << fileInfo.canonicalFilePath();
从您给出的示例路径来看,您在一个类似Unix的系统上。然后您可以使用realpath()
来规范化您的路径。这至少存在于Linux、BSD和Mac操作系统上。
http://man7.org/linux/man-pages/man3/realpath.3.html
现在可以从标准库(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;
}
文件:
https://en.cppreference.com/w/cpp/filesystem/canonical
https://en.cppreference.com/w/cpp/header/filesystem
相关文章:
- 如何将更多文件夹添加到c++include路径
- 从函数角度看ID到文件路径的内部与外部映射
- 在C++中设置基于操作系统的文件路径
- C++17 文件系统::remove_all 带有通配符路径
- 从 C 中的变量获取文件的路径,C++
- 将共享库的搜索路径更改为生成文件中提供的 rpath
- 修改生成文件以简化框架 #include 路径
- 将Visual Studio Code路径设置为.clang_format文件
- Windows 非 ASCII 文件路径
- 非 ASCII 文件路径窗口
- C++和带有国家符号的文件路径(也许用 UTF8 编码)
- 获取 H5::D ataSet 的hid_t和文件中的路径以使用 H5OCopy
- 在特定 Unicode 路径中创建文件
- 如何让用户在 tinyxml2 中输入 XML 文件的路径
- 如何将COM .tlb文件导入具有相对路径C++文件中?
- C++ 路径文件存在限制为 260 个字符
- QT-在pro中指定DLL路径.文件
- 路径文件存在导致链接器错误 2028/2019
- 选择QTableWidgetItem qt的路径文件
- 如何有一个正确的路径文件读取它到stringstream