如何解析文件路径

问题描述 投票:0回答:3

我需要创建一个函数来删除诸如“..”或“.”之类的任何内容在文件路径中。所以如果我做

resolvePath("/root\\\\directory1/directory2\\\\\\\\..")
它会返回
"root/directory1
。我尝试为路径的每一部分制作一个 char* 数组,但我无法获取它的每一段。

c++ qt boost filepath
3个回答
4
投票

两个真正跨平台的选择是 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();

2
投票

从您提供的示例路径来看,您使用的是类 Unix 系统。然后,您可以使用

realpath()
规范化您的路径。这至少存在于 Linux、BSD 和 Mac OS 上。

http://man7.org/linux/man-pages/man3/realpath.3.html


0
投票

标准库 (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

© www.soinside.com 2019 - 2024. All rights reserved.