Back to index

salome-kernel  6.5.0
Basics_DirUtils.cxx
Go to the documentation of this file.
00001 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
00002 //
00003 // This library is free software; you can redistribute it and/or
00004 // modify it under the terms of the GNU Lesser General Public
00005 // License as published by the Free Software Foundation; either
00006 // version 2.1 of the License.
00007 //
00008 // This library is distributed in the hope that it will be useful,
00009 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00010 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00011 // Lesser General Public License for more details.
00012 //
00013 // You should have received a copy of the GNU Lesser General Public
00014 // License along with this library; if not, write to the Free Software
00015 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
00016 //
00017 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
00018 //
00019 
00020 //  File   : Basics_DirUtils.cxx
00021 //  Autor  : Alexander A. BORODIN
00022 //  Module : SALOME
00023 //
00024 #include "Basics_DirUtils.hxx"
00025 #include <stdio.h>
00026 #include <errno.h>
00027 #include <stdlib.h>
00028 
00029 #ifndef WIN32
00030 # include <sys/stat.h>
00031 # include <dirent.h>
00032 #else
00033 # include <windows.h>
00034 # include <time.h>
00035 #endif
00036 
00037 #ifdef WIN32
00038 # define _separator_ '\\'
00039 #else
00040 # define _separator_ '/'
00041 #endif
00042 
00043 namespace Kernel_Utils
00044 {
00045   std::string GetBaseName( const std::string& file_path )
00046   {
00047     int pos = file_path.rfind( _separator_ );
00048     if ( pos >= 0 )
00049       return pos < (int)file_path.size()-1 ? file_path.substr( pos+1 ) : "";
00050     return file_path;
00051   }
00052 
00053   std::string GetDirName( const std::string& file_path )
00054   {
00055     int pos = file_path.rfind( _separator_ );
00056     if ( pos >= 0 )
00057       return pos < (int)file_path.size()-1 ? file_path.substr(0, pos ) : "";
00058     return std::string(".");
00059   }
00060 
00061   std::string GetTmpDirByEnv( const std::string& tmp_path_env )
00062   {
00063     char* val = getenv( tmp_path_env.c_str() );
00064     std::string dir = val ? val : "";
00065     return GetTmpDirByPath( dir );
00066   }
00067 
00068   std::string GetTmpDirByPath( const std::string& tmp_path )
00069   {
00070     std::string aTmpDir = tmp_path;
00071     if ( aTmpDir == "" )
00072       {
00073 #ifdef WIN32
00074         char *Tmp_dir = getenv("TEMP");
00075         if( Tmp_dir == NULL )
00076           {
00077             Tmp_dir = getenv("TMP");
00078             if (Tmp_dir == NULL)
00079               aTmpDir = std::string("C:\\");
00080             else 
00081               aTmpDir = std::string(Tmp_dir);
00082           }
00083         else
00084           aTmpDir = std::string(Tmp_dir);
00085 #else
00086         aTmpDir = std::string("/tmp/");
00087 #endif
00088       }
00089     
00090     if(aTmpDir[aTmpDir.size()-1] != _separator_)
00091       aTmpDir+=_separator_;
00092     
00093     srand((unsigned int)time(NULL));
00094     int aRND = 999 + (int)(100000.0*rand()/(RAND_MAX+1.0)); //Get a random number to present a name of a sub directory
00095     char buffer[127];
00096     sprintf(buffer, "%d", aRND);
00097     std::string aSubDir(buffer);
00098     if(aSubDir.size() <= 1) aSubDir = std::string("123409876");
00099     
00100     aTmpDir += aSubDir; //Get RND sub directory
00101     
00102     std::string aDir = aTmpDir;
00103     
00104     if(IsExists(aDir)) {
00105       for(aRND = 0; IsExists(aDir); aRND++) {
00106         sprintf(buffer, "%d", aRND);
00107         aDir = aTmpDir+buffer;  //Build a unique directory name
00108       }
00109     }
00110     
00111     if(aDir[aDir.size()-1] != _separator_) aDir += _separator_;
00112     
00113 #ifdef WIN32
00114     CreateDirectory(aDir.c_str(), NULL);
00115 #else
00116     mkdir(aDir.c_str(), 0x1ff); 
00117 #endif
00118     
00119     return aDir;
00120   }
00121   
00122   //============================================================================
00123   // function : GetTempDir
00124   // purpose  : Returns a temp directory to store created files like "/tmp/sub_dir/" 
00125   //============================================================================ 
00126   std::string GetTmpDir()
00127   {
00128     return GetTmpDirByPath( "" );
00129   }
00130 
00131   //============================================================================
00132   // function : GetTempFileName
00133   // purpose  : Returns the unique temporary file name without any extension /tmp/something/file for Unix or c:\something\file for WIN32
00134   //============================================================================ 
00135   std::string GetTmpFileName()
00136   {
00137     std::string tmpDir = GetTmpDir();
00138     std::string aFilePath = "";
00139     if(IsExists(tmpDir)) {
00140       srand((unsigned int)time(NULL));
00141       int aRND = 999 + (int)(100000.0*rand()/(RAND_MAX+1.0)); //Get a random number to present a name of a sub directory
00142       char buffer[127];
00143       sprintf(buffer, "%d", aRND);
00144       std::string aSubDir(buffer);
00145       if(aSubDir.size() <= 1) aSubDir = std::string("123409876");
00146       
00147       aFilePath = tmpDir;
00148       for(aRND = 0; IsExists(aFilePath); aRND++) {
00149         sprintf(buffer, "%d", aRND);
00150         aFilePath = tmpDir+buffer;  //Build a unique file name
00151       }
00152     }
00153     return aFilePath;
00154   }
00155   
00156   //============================================================================
00157   // function : IsExists
00158   // purpose  : Returns True(False) if the path (not)exists
00159   //============================================================================ 
00160   bool IsExists(const std::string& thePath) 
00161   {
00162 #ifdef WIN32 
00163     if (  GetFileAttributes (  thePath.c_str()  ) == 0xFFFFFFFF  ) { 
00164       if (  GetLastError () == ERROR_FILE_NOT_FOUND  ) {
00165         return false;
00166       }
00167     }
00168 #else 
00169     int status = access ( thePath.c_str() , F_OK ); 
00170     if (status != 0) return false;
00171 #endif
00172     return true;
00173   }
00174 
00175   //============================================================================
00176   // function : IsWritable
00177   // purpose  : Returns True(False) if the path is (not) writable
00178   //============================================================================ 
00179   bool IsWritable(const std::string& thePath) 
00180   {
00181 #ifdef WIN32 
00182     if (  GetFileAttributes (  thePath.c_str()  ) == 0xFFFFFFFF  ) { 
00183       if (  GetLastError () == FILE_ATTRIBUTE_READONLY ) {
00184         return false;
00185       }
00186     }
00187 #else 
00188     int status = access(thePath.c_str(),W_OK); 
00189     if (status != 0) return false;
00190 #endif
00191     return true;
00192   }
00193 
00194 
00195   //============================================================================
00196   // function : GetDirByPath
00197   // purpose  : Returns directory by path and converts it to native system format
00198   //============================================================================ 
00199   std::string GetDirByPath(const std::string& thePath)
00200   {
00201     if (thePath.empty())
00202       return "";
00203     std::string path = thePath;
00204     std::string::size_type length = path.length();
00205 
00206     //detect all separators in Unix format
00207     for ( unsigned int i = 0; i < length; i++ )
00208     {
00209       if( path[i] == '/' )
00210         path[i] = '|';
00211     }
00212 
00213     //detect all separators in Windows format
00214     for ( unsigned int i = 0; i < length; i++ )
00215     {
00216       if( path[i] == '\\' )
00217         path[i] = '|';
00218     }
00219 
00220 
00221     std::string::size_type pos = path.rfind('|');
00222     if ( pos == std::string::npos )
00223     {
00224 #ifdef WIN32
00225       //check for disk letter ( C: )
00226       if ( path.length() == 2 && path[1] == ':' )
00227         path += _separator_;
00228 #else
00229       //not valid path
00230       return "";
00231 #endif
00232     }
00233     else
00234     {
00235       //remove right subdirectory or filename from path
00236       path = path.substr( 0, pos );
00237     }
00238 
00239     length = path.length();
00240     for ( unsigned int i = 0; i < length; i++ )
00241     {
00242       if( path[i] == '|' )
00243         path[i] = _separator_;
00244     }
00245     return path;
00246   }
00247 
00248   //============================================================================
00249   // function : IsEmptyDir
00250   // purpose  : Returns True(False) if the path (not) empty
00251   //            Also returns False if the path is not valid
00252   //============================================================================ 
00253   bool IsEmptyDir(const std::string& thePath) 
00254   {
00255     if ( thePath.empty() || !IsExists(thePath))
00256       return false;
00257 
00258     bool result = false;
00259 
00260 #ifdef WIN32
00261     WIN32_FIND_DATA aFileData;
00262     HANDLE hFile = FindFirstFile( thePath.c_str(), &aFileData );
00263     if ( hFile == INVALID_HANDLE_VALUE )
00264     {
00265       //empty dir
00266       result = true;
00267     }
00268     else
00269     {
00270       //close serching. path is not empty
00271       FindClose( hFile );
00272     }
00273 #else
00274     DIR *dp;
00275     struct dirent *dirp;
00276     if((dp  = opendir(thePath.c_str())) == NULL)
00277     {
00278       //Could not open directory
00279       return false;
00280     }
00281     else
00282     {
00283       result = true; //empty if no file found
00284       while ((dirp = readdir(dp)) != NULL && result )
00285         {
00286           std::string file_name(dirp->d_name);
00287           result = file_name.empty() || file_name == "." || file_name == ".."; //if any file - break and return false
00288         }
00289         closedir(dp);
00290     }
00291 #endif
00292     return result;
00293   }
00294 }