Ver Fonte

Added FileSystem::dirname()

dirname() returns the directory name of the given path.
Darryl Gough há 12 anos atrás
pai
commit
b7751af3d2
2 ficheiros alterados com 61 adições e 0 exclusões
  1. 44 0
      gameplay/src/FileSystem.cpp
  2. 17 0
      gameplay/src/FileSystem.h

+ 44 - 0
gameplay/src/FileSystem.cpp

@@ -10,9 +10,12 @@
     #include <windows.h>
     #include <tchar.h>
     #include <stdio.h>
+    #include <direct.h>
     #define gp_stat _stat
     #define gp_stat_struct struct stat
 #else
+    #define __EXT_POSIX2
+    #include <libgen.h>
     #include <dirent.h>
     #define gp_stat stat
     #define gp_stat_struct struct stat
@@ -560,6 +563,47 @@ void FileSystem::createFileFromAsset(const char* path)
 #endif
 }
 
+std::string FileSystem::dirname(const char* path)
+{
+    if (path == NULL || strlen(path) == 0)
+    {
+        return "";
+    }
+#ifdef WIN32
+    char drive[_MAX_DRIVE];
+    char dir[_MAX_DIR];
+    _splitpath(path, drive, dir, NULL, NULL);
+    std::string dirname;
+    size_t driveLength = strlen(drive);
+    if (driveLength > 0)
+    {
+        dirname.reserve(driveLength + strlen(dir));
+        dirname.append(drive);
+        dirname.append(dir);
+    }
+    else
+    {
+        dirname.assign(dir);
+    }
+    std::replace(dirname.begin(), dirname.end(), '\\', '/');
+    return dirname;
+#else
+    // dirname() modifies the input string so create a temp string
+    std::string dirname;
+    char* tempPath = new char[strlen(path)];
+    strcpy(tempPath, path);
+    char* dir = ::dirname(tempPath);
+    if (dir && strlen(dir) > 0)
+    {
+        dirname.assign(dir);
+        // dirname() strips off the trailing '/' so add it back to be consistent with Windows
+        dirname.append("/");
+    }
+    SAFE_DELETE_ARRAY(tempPath);
+    return dirname;
+#endif
+}
+
 std::string FileSystem::getExtension(const char* path)
 {
     const char* str = strrchr(path, '.');

+ 17 - 0
gameplay/src/FileSystem.h

@@ -2,6 +2,7 @@
 #define FILESYSTEM_H_
 
 #include "Stream.h"
+#include <string>
 
 namespace gameplay
 {
@@ -181,6 +182,22 @@ public:
      */
     static void createFileFromAsset(const char* path);
 
+    /**
+     * Returns the directory name up to and including the trailing '/'.
+     * 
+     * This is a lexical method so it does not verify that the directory exists.
+     * Back slashes will be converted to forward slashes.
+     * 
+     * - "res/image.png" will return "res/"
+     * - "image.png" will return ""
+     * - "c:\foo\bar\image.png" will return "c:/foo/bar/"
+     * 
+     * @param The file path. May be relative or absolute, forward or back slashes. May be NULL.
+     * 
+     * @return The directory name with the trailing '/'. Returns "" if path is NULL or the path does not contain a directory.
+     */
+    static std::string dirname(const char* path);
+
     /**
      * Returns the extension of the given file path.
      *