如何获取存储在 hpp 头文件中的相对或绝对文件路径,可以在任何系统中使用?
How do I get relative or absolute file path stored in hpp header files, that can be used in any system?
我想将文件夹的绝对路径存储在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
,然后HOMEDRIVE
和HOMEPATH
,如果这些都没有设置,那么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 扩展,这意味着许多其他符号(包括*
、字符集和其他环境变量)将被扩展,这可能是不需要的。这很简单,跨平台,而且范围有限。
- 从函数角度看ID到文件路径的内部与外部映射
- 在C++中设置基于操作系统的文件路径
- Windows 非 ASCII 文件路径
- 非 ASCII 文件路径窗口
- C++和带有国家符号的文件路径(也许用 UTF8 编码)
- 如何为文件路径使用变量?
- 包括 VS Code 上的完整文件路径
- 如何使用提升获取当前文件路径?
- 如何在 c++ 中获取当前文件路径?
- 保存json文件后如何返回文件路径
- 从 C++ 中的文件路径中提取文件名
- 是否可以将文件路径传递给Qt中的setStyleSheet()
- 无法转换 .CATPart 文件.错误:输入文件路径似乎包含不支持的字符
- 在结构函数之间传递文件路径 C++ 编辑:修复LNK2019错误
- 提供依赖于输入的程序的文件路径
- 从 QFileSystemModel 中的文件路径和文件名获取 QModelIndex
- 如何更改变量文件名的文件路径?
- cmake:包括vs vs add_subDirectory:相对标头文件路径
- 在OSX中使用CGDisplayStream存储屏幕记录的特定文件路径
- 如何在另一个系统上启用文件路径