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