如何正确处理带有std::filesystem::path的长路径前缀的windows路径



std::filesystem::path似乎不知道windows长路径魔术前缀。这是否符合设计,或者是否有可以使用的模式/标志/编译器开关/第三方库?

f.e.

  • 对于像C:temptest.txt这样的路径,root_nameC:root_pathC:,它们都是有效路径,但是
  • 对于\?C:tmptest.txt,它们是\?\?

我希望它们也是C:C:,因为\?不是一个路径,而是一个用于绕过遗留windows 260字符路径限制的标签。

请参阅compilereexplorer上的完整示例。

正如上面的评论中所提到的,Microsoft STL的源代码表明,当前行为是针对UNC(统一命名约定(路径的,并且不存在"魔术编译器开关";来改变这一点。此外,正如这篇github文章所暗示的那样,UNC路径似乎不应该与std::filesystem一起使用。还有一个悬而未决的问题要求改变行为。

由于OP适用于第三方库:boost::filesystem在Windows构建中为UNC路径提供了特殊代码,并给出了更接近预期的结果。

尝试使用以下代码(改编自原始帖子(:

#include <filesystem>
#include <iostream>
#include <string>
#include <vector>
#include <boost/filesystem.hpp>
int main()
{
std::vector<std::string> tests = {
R"(C:temptest.txt)",
R"(\?C:temptest.txt)",
};
for (auto const & test : tests) {
std::filesystem::path const p(test); // or boost::filesystem::path
std::cout << std::endl << test << std::endl;
std::cout << "root_namet" << p.root_name().string() << std::endl;
std::cout << "root_directoryt" << p.root_directory().string() << std::endl;
std::cout << "root_patht" << p.root_path().string() << std::endl;
std::cout << "relative_patht" << p.relative_path().string() << std::endl;
std::cout << "parent_patht" << p.parent_path().string() << std::endl;
std::cout << "filenamet" << p.filename().string() << std::endl;
std::cout << "stemt" << p.stem().string() << std::endl;
std::cout << "extensiont" << p.extension().string() << std::endl;
}
}

对于MSVC上的std::filesystem,我得到

C:temptest.txt
root_name       C:
root_directory  
root_path       C:
relative_path   temptest.txt
parent_path     C:temp
filename        test.txt
stem    test
extension       .txt
\?C:temptest.txt
root_name       \?
root_directory  
root_path       \?
relative_path   C:temptest.txt
parent_path     \?C:temp
filename        test.txt
stem    test
extension       .txt

对于boost::filesystem,我得到:

C:temptest.txt
root_name       C:
root_directory  
root_path       C:
relative_path   temptest.txt
parent_path     C:temp
filename        test.txt
stem    test
extension       .txt
\?C:temptest.txt
root_name       \?C:
root_directory  
root_path       \?C:
relative_path   temptest.txt
parent_path     \?C:temp
filename        test.txt
stem    test
extension       .txt

最新更新