Détecter si le chemin est absolu ou relatif

En utilisant C ++, je dois détecter si le chemin donné (nom de fichier) est absolu ou relatif. Je peux utiliser l’API Windows, mais je ne veux pas utiliser de bibliothèques tierces comme Boost, car j’ai besoin de cette solution dans une petite application Windows sans dépendances externes.

L’API Windows a PathIsRelative . Il est défini comme suit:

 BOOL PathIsRelative( _In_ LPCTSTR lpszPath ); 

A partir de C ++ 14 / C ++ 17, vous pouvez utiliser is_absolute() et is_relative() de la bibliothèque de systèmes de fichiers

 #include  // C++17 (or Microsoft-specific implementation in C++14) std::ssortingng winPathSsortingng = "C:/tmp"; std::filesystem::path path(winPathSsortingng); // Construct the path from a ssortingng. if (path.is_absolute()) { // Arriving here if winPathSsortingng = "C:/tmp". } if (path.is_relative()) { // Arriving here if winPathSsortingng = "". // Arriving here if winPathSsortingng = "tmp". // Arriving here in windows if winPathSsortingng = "/tmp". (see quote below) } 

Le chemin “/” est absolu sur un système d’exploitation POSIX, mais est relatif sous Windows.

En C ++ 14, utilisez std::experimental::filesystem

 #include  // C++14 std::experimental::filesystem::path path(winPathSsortingng); // Construct the path from a ssortingng. 

J’ai le boost 1.63 et VS2010 (c ++ pre c ++ 11), et le code suivant fonctionne.

 std::filesystem::path path(winPathSsortingng); // Construct the path from a ssortingng. if (path.is_absolute()) { // Arriving here if winPathSsortingng = "C:/tmp". }