提取文件路径的完整扩展名

Extract full extension of file path

使用 std::filesystem,并给出像 /path/to/file.tar.gz 这样的路径,我如何提取 fullcomplete 文件扩展名 - 在这种情况下 tar.gz?

看来 std::filesystem::extension() 只是 returns 文件名中最后一个点之后的片段。使用上面指定的路径,结果将是 .gz.

Qt 为此提供了QFileInfo::completeSuffix()。根据 C++20,std::filesystem 中是否有等效项?

在 Linux 系统上,文件路径中可以有很多点。例如 /tmp/some.nice.looking....file.here.txt 是一个有效的文件路径。另请参阅 path_resolution(7) and file(1) and observe that a file path which is (in C notation) "/\n" is valid (but ugly) - at least inside some ext4(5) 文件系统。

此外,文件路径可以(按照惯例或用户错误)包含空格、制表符或奇怪的 UTF-8 characters. Think of some USB key with some VFAT file system written on a Windows laptop used by a Russian mathematician writing some paper in LaTeX about λ-calculus - he/she 可以使用 λ 和 his/her 西里尔姓氏。

并且您可以拥有一些定义新的常规后缀的应用程序。例如,我的 Bismon 按照惯例使用 .bmon 扩展名。

一种可能性是限制您的应用程序(按照记录的约定)处理 /etc/mime.types

中列出的扩展

然后您的应用程序将在启动时解析 /etc/mime.types,并收集一组可能的文件扩展名。

这个没有专门的方法,但是你可以通过简单的字符串操作来实现它:

std::filesystem::path path = "/path/to/file.tar.gz";
std::string filename = path.filename().string();
std::string extension(std::find(filename.begin(), filename.end(), '.'), filename.end());