如何获取存储在 hpp 头文件中的相对或绝对文件路径,可以在任何系统中使用?

How do I get relative or absolute file path stored in hpp header files, that can be used in any system?

本文关键字:文件 路径 系统 任何 获取 何获取 存储 相对 hpp      更新时间:2023-10-16

我想将文件夹的绝对路径存储在hpp文件中;该路径存储在公共类中。我尝试使用:static constexpr const char* FOLDER_PATH = "$HOME/catkin_ws/src/abc/pqr/xyz"

但是,这种$HOME似乎不起作用。我可以获得$HOME解决方法吗?如果我写/home/myname/它似乎工作正常。我不想写/home/myname/;问题是每次在不同系统上运行该代码时,我都需要更改。我不想每次都编辑;文件夹结构保持不变。

C++中的跨平台主目录

要在运行时获取 HOME 目录(这意味着它不能在编译时确定,因此它不能作为常量存储在标头中),您可以使用getenv(或在 Windows 上,_wgetenv,因为路径应该是 Unicode 感知的,因此在 Windows 上使用宽 API)。

波西斯

您可以假设路径是使用HOME环境变量指定的。

#include <cstdlib>
#include <string>
std::string get_home()
{
char *dir = getenv("HOME");
if (dir != nullptr) {
return std::string(dir);
} else {
// home not defined, root user, maybe return "/root"
// this code path should generally **not** occur.  
return std::string("/");
}
}

窗户

正如Miles Budnek所建议的那样,一个简单的解决方案是使用GetUserProfileDirectory函数。

#include <windows.h>
#include <string>
std::wstring get_home()
{
DWORD size = 0;
HANDLE token = GetCurrentProcessToken();
// get the size needed for the buffer.
GetUserProfileDirectoryW(token, NULL, &size);
if (size == 0) {
throw std::runtime_error("Unable to get required size.n");
}
// this won't work pre-C++11, since strings weren't guaranteed
// to be continuous
std::wstring home(size, 0);
if (!GetUserProfileDirectoryW(token, &home[0], &size)) {
throw std::runtime_error(("Unable to get home directory.n");
}
return home;
}

如果你想依赖环境变量,这并不容易,但最好的解决方案是检查USERPROFILE,然后HOME,然后HOMEDRIVEHOMEPATH,如果这些都没有设置,那么SystemDrive作为回退。这适用于:

#include <cstdlib>
#include <stdexcept>
#include <string>
std::wstring get_home()
{
// check USERPROFILE
wchar_t *home = _wgetenv(L"USERPROFILE");
if (home != nullptr) {
return std::wstring(home);
}
// check HOME
home = _wgetenv(L"HOME");
if (home != nullptr) {
return std::wstring(home);
}
// combine HOMEDRIVE and HOMEPATH
wchar_t *drive = _wgetenv(L"HOMEDRIVE");
wchar_t *path = _wgetenv(L"HOMEPATH");
if (drive != nullptr && path != nullptr) {
// "c:", "users{user}"
return std::wstring(drive) + std::wstring(path);
}
// try SystemDrive
home = _wgetenv(L"SystemDrive");
if (home != nullptr) {
return std::wstring(home);
} else {
return std::wstring(L"c:");
}
}

为什么不是WordExp?

wordexp不能保证是Windows编译器的一部分,并且在Windows上不能很好地工作。此外,HOME不保证在 Windows 上设置。您应该使用(_w)getenv.此外,wordexp进行 shell 扩展,这意味着许多其他符号(包括*、字符集和其他环境变量)将被扩展,这可能是不需要的。这很简单,跨平台,而且范围有限。