Salome HOME
add test MPI2 communication
[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 GetDirName( const std::string& file_path )
54   {
55     int pos = file_path.rfind( _separator_ );
56     if ( pos >= 0 )
57       return pos < (int)file_path.size()-1 ? file_path.substr(0, pos ) : "";
58     return std::string(".");
59   }
60
61   std::string GetTmpDirByEnv( const std::string& tmp_path_env )
62   {
63     char* val = getenv( tmp_path_env.c_str() );
64     std::string dir = val ? val : "";
65     return GetTmpDirByPath( dir );
66   }
67
68   std::string GetTmpDirByPath( const std::string& tmp_path )
69   {
70     std::string aTmpDir = tmp_path;
71     if ( aTmpDir == "" )
72       {
73 #ifdef WIN32
74         char *Tmp_dir = getenv("TEMP");
75         if( Tmp_dir == NULL )
76           {
77             Tmp_dir = getenv("TMP");
78             if (Tmp_dir == NULL)
79               aTmpDir = std::string("C:\\");
80             else 
81               aTmpDir = std::string(Tmp_dir);
82           }
83         else
84           aTmpDir = std::string(Tmp_dir);
85 #else
86         aTmpDir = std::string("/tmp/");
87 #endif
88       }
89     
90     if(aTmpDir[aTmpDir.size()-1] != _separator_)
91       aTmpDir+=_separator_;
92     
93     srand((unsigned int)time(NULL));
94     int aRND = 999 + (int)(100000.0*rand()/(RAND_MAX+1.0)); //Get a random number to present a name of a sub directory
95     char buffer[127];
96     sprintf(buffer, "%d", aRND);
97     std::string aSubDir(buffer);
98     if(aSubDir.size() <= 1) aSubDir = std::string("123409876");
99     
100     aTmpDir += aSubDir; //Get RND sub directory
101     
102     std::string aDir = aTmpDir;
103     
104     if(IsExists(aDir)) {
105       for(aRND = 0; IsExists(aDir); aRND++) {
106         sprintf(buffer, "%d", aRND);
107         aDir = aTmpDir+buffer;  //Build a unique directory name
108       }
109     }
110     
111     if(aDir[aDir.size()-1] != _separator_) aDir += _separator_;
112     
113 #ifdef WIN32
114     CreateDirectory(aDir.c_str(), NULL);
115 #else
116     mkdir(aDir.c_str(), 0x1ff); 
117 #endif
118     
119     return aDir;
120   }
121   
122   //============================================================================
123   // function : GetTempDir
124   // purpose  : Returns a temp directory to store created files like "/tmp/sub_dir/" 
125   //============================================================================ 
126   std::string GetTmpDir()
127   {
128     return GetTmpDirByPath( "" );
129   }
130
131   //============================================================================
132   // function : GetTempFileName
133   // purpose  : Returns the unique temporary file name without any extension /tmp/something/file for Unix or c:\something\file for WIN32
134   //============================================================================ 
135   std::string GetTmpFileName()
136   {
137     std::string tmpDir = GetTmpDir();
138     std::string aFilePath = "";
139     if(IsExists(tmpDir)) {
140       srand((unsigned int)time(NULL));
141       int aRND = 999 + (int)(100000.0*rand()/(RAND_MAX+1.0)); //Get a random number to present a name of a sub directory
142       char buffer[127];
143       sprintf(buffer, "%d", aRND);
144       std::string aSubDir(buffer);
145       if(aSubDir.size() <= 1) aSubDir = std::string("123409876");
146       
147       aFilePath = tmpDir;
148       for(aRND = 0; IsExists(aFilePath); aRND++) {
149         sprintf(buffer, "%d", aRND);
150         aFilePath = tmpDir+buffer;  //Build a unique file name
151       }
152     }
153     return aFilePath;
154   }
155   
156   //============================================================================
157   // function : IsExists
158   // purpose  : Returns True(False) if the path (not)exists
159   //============================================================================ 
160   bool IsExists(const std::string& thePath) 
161   {
162 #ifdef WIN32 
163     if (  GetFileAttributes (  thePath.c_str()  ) == 0xFFFFFFFF  ) { 
164       if (  GetLastError () == ERROR_FILE_NOT_FOUND  ) {
165         return false;
166       }
167     }
168 #else 
169     int status = access ( thePath.c_str() , F_OK ); 
170     if (status != 0) return false;
171 #endif
172     return true;
173   }
174
175   //============================================================================
176   // function : IsWritable
177   // purpose  : Returns True(False) if the path is (not) writable
178   //============================================================================ 
179   bool IsWritable(const std::string& thePath) 
180   {
181 #ifdef WIN32 
182     if (  GetFileAttributes (  thePath.c_str()  ) == 0xFFFFFFFF  ) { 
183       if (  GetLastError () == FILE_ATTRIBUTE_READONLY ) {
184         return false;
185       }
186     }
187 #else 
188     int status = access(thePath.c_str(),W_OK); 
189     if (status != 0) return false;
190 #endif
191     return true;
192   }
193
194
195   //============================================================================
196   // function : GetDirByPath
197   // purpose  : Returns directory by path and converts it to native system format
198   //============================================================================ 
199   std::string GetDirByPath(const std::string& thePath)
200   {
201     if (thePath.empty())
202       return "";
203     std::string path = thePath;
204     std::string::size_type length = path.length();
205
206     //detect all separators in Unix format
207     for ( unsigned int i = 0; i < length; i++ )
208     {
209       if( path[i] == '/' )
210         path[i] = '|';
211     }
212
213     //detect all separators in Windows format
214     for ( unsigned int i = 0; i < length; i++ )
215     {
216       if( path[i] == '\\' )
217         path[i] = '|';
218     }
219
220
221     std::string::size_type pos = path.rfind('|');
222     if ( pos == std::string::npos )
223     {
224 #ifdef WIN32
225       //check for disk letter ( C: )
226       if ( path.length() == 2 && path[1] == ':' )
227         path += _separator_;
228 #else
229       //not valid path
230       return "";
231 #endif
232     }
233     else
234     {
235       //remove right subdirectory or filename from path
236       path = path.substr( 0, pos );
237     }
238
239     length = path.length();
240     for ( unsigned int i = 0; i < length; i++ )
241     {
242       if( path[i] == '|' )
243         path[i] = _separator_;
244     }
245     return path;
246   }
247
248   //============================================================================
249   // function : IsEmptyDir
250   // purpose  : Returns True(False) if the path (not) empty
251   //            Also returns False if the path is not valid
252   //============================================================================ 
253   bool IsEmptyDir(const std::string& thePath) 
254   {
255     if ( thePath.empty() || !IsExists(thePath))
256       return false;
257
258     bool result = false;
259
260 #ifdef WIN32
261     WIN32_FIND_DATA aFileData;
262     HANDLE hFile = FindFirstFile( thePath.c_str(), &aFileData );
263     if ( hFile == INVALID_HANDLE_VALUE )
264     {
265       //empty dir
266       result = true;
267     }
268     else
269     {
270       //close serching. path is not empty
271       FindClose( hFile );
272     }
273 #else
274     DIR *dp;
275     struct dirent *dirp;
276     if((dp  = opendir(thePath.c_str())) == NULL)
277     {
278       //Could not open directory
279       return false;
280     }
281     else
282     {
283       result = true; //empty if no file found
284       while ((dirp = readdir(dp)) != NULL && result )
285         {
286           std::string file_name(dirp->d_name);
287           result = file_name.empty() || file_name == "." || file_name == ".."; //if any file - break and return false
288         }
289         closedir(dp);
290     }
291 #endif
292     return result;
293   }
294 }