dirtools_public.cpp (2069B)
1 //========= Copyright Valve Corporation ============// 2 #include "dirtools_public.h" 3 #include "strtools_public.h" 4 #include "pathtools_public.h" 5 6 #include <errno.h> 7 #include <string.h> 8 9 #ifdef _WIN32 10 #include "windows.h" 11 #else 12 #include <stdlib.h> 13 #include <stdio.h> 14 #include <sys/stat.h> 15 #include <sys/types.h> 16 #endif 17 18 #if defined( OSX ) 19 #include <sys/syslimits.h> 20 #endif 21 22 23 //----------------------------------------------------------------------------- 24 // Purpose: utility function to create dirs & subdirs 25 //----------------------------------------------------------------------------- 26 bool BCreateDirectoryRecursive( const char *pchPath ) 27 { 28 // Does it already exist? 29 if ( Path_IsDirectory( pchPath ) ) 30 return true; 31 32 // copy the path into something we can munge 33 int len = (int)strlen( pchPath ); 34 char *path = (char *)malloc( len + 1 ); 35 strcpy( path, pchPath ); 36 37 // Walk backwards to first non-existing dir that we find 38 char *s = path + len - 1; 39 40 const char slash = Path_GetSlash(); 41 while ( s > path ) 42 { 43 if ( *s == slash ) 44 { 45 *s = '\0'; 46 bool bExists = Path_IsDirectory( path ); 47 *s = slash; 48 49 if ( bExists ) 50 { 51 ++s; 52 break; 53 } 54 } 55 --s; 56 } 57 58 // and then move forwards from there 59 60 while ( *s ) 61 { 62 if ( *s == slash ) 63 { 64 *s = '\0'; 65 BCreateDirectory( path ); 66 *s = slash; 67 } 68 s++; 69 } 70 71 bool bRetVal = BCreateDirectory( path ); 72 free( path ); 73 return bRetVal; 74 } 75 76 77 //----------------------------------------------------------------------------- 78 // Purpose: Creates the directory, returning true if it is created, or if it already existed 79 //----------------------------------------------------------------------------- 80 bool BCreateDirectory( const char *pchPath ) 81 { 82 #ifdef WIN32 83 std::wstring wPath = UTF8to16( pchPath ); 84 if ( ::CreateDirectoryW( wPath.c_str(), NULL ) ) 85 return true; 86 87 if ( ::GetLastError() == ERROR_ALREADY_EXISTS ) 88 return true; 89 90 return false; 91 #else 92 int i = mkdir( pchPath, S_IRWXU | S_IRWXG | S_IRWXO ); 93 if ( i == 0 ) 94 return true; 95 if ( errno == EEXIST ) 96 return true; 97 98 return false; 99 #endif 100 }