Используя С++, мне нужно определить, является ли данный путь (имя файла) абсолютным или относительным. Я могу использовать Windows API, но не хочу использовать сторонние библиотеки, такие как Boost, так как мне нужно это решение в небольшом приложении Windows без зависимостей от эксперимента.
Определить, является ли путь абсолютным или относительным
Ответ 1
В Windows API есть PathIsRelative
. Он определяется как:
BOOL PathIsRelative(
_In_ LPCTSTR lpszPath
);
Ответ 2
Начиная с С++ 14/С++ 17 вы можете использовать is_absolute()
и is_relative()
из файловой системы
#include <filesystem> // C++17 (or Microsoft-specific implementation in C++14)
std::string winPathString = "C:/tmp";
std::filesystem::path path(winPathString); // Construct the path from a string.
if (path.is_absolute()) {
// Arriving here if winPathString = "C:/tmp".
}
if (path.is_relative()) {
// Arriving here if winPathString = "".
// Arriving here if winPathString = "tmp".
// Arriving here in windows if winPathString = "/tmp". (see quote below)
}
Путь "/" является абсолютным на ОС POSIX, но относительно Windows.
В С++ 14 используйте std::experimental::filesystem
#include <experimental/filesystem> // C++14
std::experimental::filesystem::path path(winPathString); // Construct the path from a string.
Ответ 3
У меня есть boost 1.63 и VS2010 (С++ pre С++ 11), и работает следующий код.
std::filesystem::path path(winPathString); // Construct the path from a string.
if (path.is_absolute()) {
// Arriving here if winPathString = "C:/tmp".
}