gpt4 book ai didi

c++ - 如何获取 linux 的已知路径

转载 作者:太空狗 更新时间:2023-10-29 20:50:08 24 4
gpt4 key购买 nike

Windows 有一个已知路径的概念,其中包含无需硬编码路径即可检索它们的函数:

#include <filesystem>
#include <windows.h>
#include <ShlObj.h>
//...
std::filesystem::path GetAppDataPath() {
namespace FS = std::filesystem;
PWSTR ppszPath = nullptr;
auto hr_path = ::SHGetKnownFolderPath(FOLDERID_RoamingAppData, KF_FLAG_DEFAULT, nullptr, &ppszPath);
bool success = SUCCEEDED(hr_path);
if (success) {
auto p = FS::path(ppszPath);
::CoTaskMemFree(ppszPath);
p = FS::canonical(p);
return p;
}
return {};
}

是否有 linux 的等价物?

最佳答案

Linux 是一个操作系统内核。它没有用户目录的概念。

有几种 Linux 发行版。文件系统结构由发行版决定。大多数发行版符合 POSIX standard ,并(在不同程度上)遵循 Filesystem Hierarchy Standard由 Linux Foundation 提供,它类似于其他类 UNIX 系统的目录结构。也就是说,发行版通常允许用户以非常规配置使用文件系统。例如,他们通常不会强制用户主目录位于 /home 下。

POSIX 指定了一些与此上下文相关的环境变量:

HOME

The system shall initialize this variable at the time of login to be a pathname of the user's home directory.

TMPDIR

This variable shall represent a pathname of a directory made available for programs that need a place to create temporary files.

在 C++ 中可以使用 std::getenv 访问环境变量。


在桌面系统上,目录结构在某种程度上也由桌面环境决定,其中有几种可用。 freedesktop.org 为不同桌面环境的互操作性制定了非官方规范。在 DE 上符合 XDG Base Directory Specification应提供以下环境变量:

$XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored. If $XDG_DATA_HOME is either not set or empty, a default equal to $HOME/.local/share should be used.

$XDG_CONFIG_HOME defines the base directory relative to which user specific configuration files should be stored. If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config should be used.

$XDG_DATA_DIRS defines the preference-ordered set of base directories to search for data files in addition to the $XDG_DATA_HOME base directory. The directories in $XDG_DATA_DIRS should be seperated with a colon ':'.

If $XDG_DATA_DIRS is either not set or empty, a value equal to /usr/local/share/:/usr/share/ should be used.

freedesktop.org 还提供了一个实用程序 xdg-user-dirs :

xdg-user-dirs is a tool to help manage "well known" user directories like the desktop folder and the music folder. It also handles localization (i.e. translation) of the filenames.

$(XDG_CONFIG_HOME)/user-dirs.dirs specifies the current set of directories for the user. This file is in a shell format, so its easy to access from a shell script. This file can also be modified by users (manually or via applications) to change the directories used.


因此,在 FOLDERID_RoamingAppData 的情况下,您可能应该根据用例使用 $XDG_x 之一,回退到相对于 $ 的适当默认值HOME 指定。

关于c++ - 如何获取 linux 的已知路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56364165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com