]> SALOME platform Git repositories - modules/kernel.git/blob - src/Basics/Basics_DirUtils.cxx
Salome HOME
Merge from V6_3_BR 06/06/2011
[modules/kernel.git] / src / Basics / Basics_DirUtils.cxx
1 // Copyright (C) 2007-2011  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 //  File   : Basics_DirUtils.cxx
21 //  Autor  : Alexander A. BORODIN
22 //  Module : SALOME
23 //
24 #include "Basics_DirUtils.hxx"
25 #include <stdio.h>
26 #include <errno.h>
27 #include <stdlib.h>
28
29 #ifndef WIN32
30 # include <sys/stat.h>
31 # include <dirent.h>
32 #else
33 # include <windows.h>
34 # include <time.h>
35 #endif
36
37 #ifdef WIN32
38 # define _separator_ '\\'
39 #else
40 # define _separator_ '/'
41 #endif
42
43 namespace Kernel_Utils
44 {
45   std::string GetBaseName( const std::string& file_path )
46   {
47     int pos = file_path.rfind( _separator_ );
48     if ( pos >= 0 )
49       return pos < (int)file_path.size()-1 ? file_path.substr( pos+1 ) : "";
50     return file_path;
51   }
52
53   std::string GetTmpDirByEnv( const std::string& tmp_path_env )
54   {
55     char* val = getenv( tmp_path_env.c_str() );
56     std::string dir = val ? val : "";
57     return GetTmpDirByPath( dir );
58   }
59
60   std::string GetTmpDirByPath( const std::string& tmp_path )
61   {
62     std::string aTmpDir = tmp_path;
63     if ( aTmpDir == "" )
64       {
65 #ifdef WIN32
66         char *Tmp_dir = getenv("TEMP");
67         if( Tmp_dir == NULL )
68           {
69             Tmp_dir = getenv("TMP");
70             if (Tmp_dir == NULL)
71               aTmpDir = std::string("C:\\");
72             else 
73               aTmpDir = std::string(Tmp_dir);
74           }
75         else
76           aTmpDir = std::string(Tmp_dir);
77 #else
78         aTmpDir = std::string("/tmp/");
79 #endif
80       }
81     
82     if(aTmpDir[aTmpDir.size()-1] != _separator_)
83       aTmpDir+=_separator_;
84     
85     srand((unsigned int)time(NULL));
86     int aRND = 999 + (int)(100000.0*rand()/(RAND_MAX+1.0)); //Get a random number to present a name of a sub directory
87     char buffer[127];
88     sprintf(buffer, "%d", aRND);
89     std::string aSubDir(buffer);
90     if(aSubDir.size() <= 1) aSubDir = std::string("123409876");
91     
92     aTmpDir += aSubDir; //Get RND sub directory
93     
94     std::string aDir = aTmpDir;
95     
96     if(IsExists(aDir)) {
97       for(aRND = 0; IsExists(aDir); aRND++) {
98         sprintf(buffer, "%d", aRND);
99         aDir = aTmpDir+buffer;  //Build a unique directory name
100       }
101     }
102     
103     if(aDir[aDir.size()-1] != _separator_) aDir += _separator_;
104     
105 #ifdef WIN32
106     CreateDirectory(aDir.c_str(), NULL);
107 #else
108     mkdir(aDir.c_str(), 0x1ff); 
109 #endif
110     
111     return aDir;
112   }
113   
114   //============================================================================
115   // function : GetTempDir
116   // purpose  : Returns a temp directory to store created files like "/tmp/sub_dir/" 
117   //============================================================================ 
118   std::string GetTmpDir()
119   {
120     return GetTmpDirByPath( "" );
121   }
122
123   //============================================================================
124   // function : GetTempFileName
125   // purpose  : Returns the unique temporary file name without any extension /tmp/something/file for Unix or c:\something\file for WIN32
126   //============================================================================ 
127   std::string GetTmpFileName()
128   {
129     std::string tmpDir = GetTmpDir();
130     std::string aFilePath = "";
131     if(IsExists(tmpDir)) {
132       srand((unsigned int)time(NULL));
133       int aRND = 999 + (int)(100000.0*rand()/(RAND_MAX+1.0)); //Get a random number to present a name of a sub directory
134       char buffer[127];
135       sprintf(buffer, "%d", aRND);
136       std::string aSubDir(buffer);
137       if(aSubDir.size() <= 1) aSubDir = std::string("123409876");
138       
139       aFilePath = tmpDir;
140       for(aRND = 0; IsExists(aFilePath); aRND++) {
141         sprintf(buffer, "%d", aRND);
142         aFilePath = tmpDir+buffer;  //Build a unique file name
143       }
144     }
145     return aFilePath;
146   }
147   
148   //============================================================================
149   // function : IsExists
150   // purpose  : Returns True(False) if the path (not)exists
151   //============================================================================ 
152   bool IsExists(const std::string& thePath) 
153   {
154 #ifdef WIN32 
155     if (  GetFileAttributes (  thePath.c_str()  ) == 0xFFFFFFFF  ) { 
156       if (  GetLastError () == ERROR_FILE_NOT_FOUND  ) {
157         return false;
158       }
159     }
160 #else 
161     int status = access ( thePath.c_str() , F_OK ); 
162     if (status != 0) return false;
163 #endif
164     return true;
165   }
166
167   //============================================================================
168   // function : GetDirByPath
169   // purpose  : Returns directory by path and converts it to native system format
170   //============================================================================ 
171   std::string GetDirByPath(const std::string& thePath)
172   {
173     if (thePath.empty())
174       return "";
175     std::string path = thePath;
176     std::string::size_type length = path.length();
177
178     //detect all separators in Unix format
179     for ( unsigned int i = 0; i < length; i++ )
180     {
181       if( path[i] == '/' )
182         path[i] = '|';
183     }
184
185     //detect all separators in Windows format
186     for ( unsigned int i = 0; i < length; i++ )
187     {
188       if( path[i] == '\\' )
189         path[i] = '|';
190     }
191
192
193     std::string::size_type pos = path.rfind('|');
194     if ( pos == std::string::npos )
195     {
196 #ifdef WIN32
197       //check for disk letter ( C: )
198       if ( path.length() == 2 && path[1] == ':' )
199         path += _separator_;
200 #else
201       //not valid path
202       return "";
203 #endif
204     }
205     else
206     {
207       //remove right subdirectory or filename from path
208       path = path.substr( 0, pos );
209     }
210
211     length = path.length();
212     for ( unsigned int i = 0; i < length; i++ )
213     {
214       if( path[i] == '|' )
215         path[i] = _separator_;
216     }
217     return path;
218   }
219
220   //============================================================================
221   // function : IsEmptyDir
222   // purpose  : Returns True(False) if the path (not) empty
223   //            Also returns False if the path is not valid
224   //============================================================================ 
225   bool IsEmptyDir(const std::string& thePath) 
226   {
227     if ( thePath.empty() || !IsExists(thePath))
228       return false;
229
230     bool result = false;
231
232 #ifdef WIN32
233     WIN32_FIND_DATA aFileData;
234     HANDLE hFile = FindFirstFile( thePath.c_str(), &aFileData );
235     if ( hFile == INVALID_HANDLE_VALUE )
236     {
237       //empty dir
238       result = true;
239     }
240     else
241     {
242       //close serching. path is not empty
243       FindClose( hFile );
244     }
245 #else
246     DIR *dp;
247     struct dirent *dirp;
248     if((dp  = opendir(thePath.c_str())) == NULL)
249     {
250       //Could not open directory
251       return false;
252     }
253     else
254     {
255       result = true; //empty if no file found
256       while ((dirp = readdir(dp)) != NULL && result )
257         {
258           std::string file_name(dirp->d_name);
259           result = file_name.empty() || file_name == "." || file_name == ".."; //if any file - break and return false
260         }
261         closedir(dp);
262     }
263 #endif
264     return result;
265   }
266 }