Visual Servoing Platform  version 3.0.0
vpIoTools.cpp
1 /****************************************************************************
2  *
3  * This file is part of the ViSP software.
4  * Copyright (C) 2005 - 2015 by Inria. All rights reserved.
5  *
6  * This software is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * ("GPL") version 2 as published by the Free Software Foundation.
9  * See the file LICENSE.txt at the root directory of this source
10  * distribution for additional information about the GNU GPL.
11  *
12  * For using ViSP with software that can not be combined with the GNU
13  * GPL, please contact Inria about acquiring a ViSP Professional
14  * Edition License.
15  *
16  * See http://visp.inria.fr for more information.
17  *
18  * This software was developed at:
19  * Inria Rennes - Bretagne Atlantique
20  * Campus Universitaire de Beaulieu
21  * 35042 Rennes Cedex
22  * France
23  *
24  * If you have questions regarding the use of this file, please contact
25  * Inria at visp@inria.fr
26  *
27  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
28  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
29  *
30  * Description:
31  * Directory management.
32  *
33  * Authors:
34  * Fabien Spindler
35  *
36  *****************************************************************************/
37 
42 #include <visp3/core/vpIoTools.h>
43 #include <visp3/core/vpDebug.h>
44 #include <visp3/core/vpIoException.h>
45 #include <stdlib.h>
46 #include <stdio.h>
47 #include <fstream>
48 #include <string.h>
49 #include <sys/stat.h>
50 #include <sys/types.h>
51 #include <fcntl.h>
52 #include <limits>
53 #include <cmath>
54 #include <algorithm>
55 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
56 # include <unistd.h>
57 #elif defined(_WIN32)
58 # include <windows.h>
59 # include <direct.h>
60 #endif
61 #if !defined(_WIN32)
62 # include <wordexp.h>
63 #endif
64 
65 std::string vpIoTools::baseName = "";
66 std::string vpIoTools::baseDir = "";
67 std::string vpIoTools::configFile = "";
68 std::vector<std::string> vpIoTools::configVars = std::vector<std::string>();
69 std::vector<std::string> vpIoTools::configValues = std::vector<std::string>();
70 
76 void vpIoTools::setBaseName(const std::string &s) {baseName = s;}
82 void vpIoTools::setBaseDir(const std::string &dir) {baseDir = dir + "/";}
88 std::string vpIoTools::getBaseName() {return baseName;}
94 std::string vpIoTools::getFullName() {return baseDir + baseName;}
95 
113 void
114 vpIoTools::getUserName(std::string &username)
115 {
116  // With MinGW, UNIX and _WIN32 are defined
117 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
118  // Get the user name.
119  char *_username = NULL;
120  _username = ::getenv("LOGNAME");
121  if (_username == NULL) {
122  vpERROR_TRACE( "Cannot get the username. Check your LOGNAME environment variable" );
124  "Cannot get the username")) ;
125  }
126  username = _username;
127 #elif defined(_WIN32)
128  unsigned int info_buffer_size = 1024;
129  TCHAR *infoBuf = new TCHAR [info_buffer_size];
130  DWORD bufCharCount = (DWORD) info_buffer_size;
131  // Get the user name.
132  if( ! GetUserName( infoBuf, &bufCharCount ) ) {
133  delete [] infoBuf;
134  vpERROR_TRACE( "Cannot get the username" );
136  "Cannot get the username")) ;
137 
138  }
139  username = infoBuf;
140  delete [] infoBuf;
141 #endif
142 }
160 std::string
162 {
163  std::string username;
164 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
165  // Get the user name.
166  char *_username = NULL;
167  _username = ::getenv("LOGNAME");
168  if (_username == NULL) {
169  vpERROR_TRACE( "Cannot get the username. Check your LOGNAME environment variable" );
171  "Cannot get the username")) ;
172  }
173  username = _username;
174 #elif defined(_WIN32)
175  unsigned int info_buffer_size = 1024;
176  TCHAR *infoBuf = new TCHAR [info_buffer_size];
177  DWORD bufCharCount = (DWORD) info_buffer_size;
178  // Get the user name.
179  if( ! GetUserName( infoBuf, &bufCharCount ) ) {
180  delete [] infoBuf;
181  vpERROR_TRACE( "Cannot get the username" );
183  "Cannot get the username")) ;
184 
185  }
186  username = infoBuf;
187  delete [] infoBuf;
188 #endif
189  return username;
190 }
191 
223 std::string
224 vpIoTools::getenv(const char *env)
225 {
226  std::string value;
227  // Get the environment variable value.
228  char *_value = NULL;
229  _value = ::getenv(env);
230  if (_value == NULL) {
231  vpERROR_TRACE( "Cannot get the environment variable value" );
233  "Cannot get the environment variable value")) ;
234  }
235  value = _value;
236 
237  return value;
238 }
239 
272 std::string
273 vpIoTools::getenv(const std::string &env)
274 {
275  return (vpIoTools::getenv(env.c_str()));
276 }
277 
287 void
288 vpIoTools::getVersion(const std::string &version, unsigned int &major, unsigned int &minor, unsigned int &patch)
289 {
290  if(version.size() == 0){
291  major = 0;
292  minor = 0;
293  patch = 0;
294  }
295  else{
296  size_t major_pos = version.find('.');
297  std::string major_str = version.substr(0, major_pos);
298  major = (unsigned)atoi(major_str.c_str());
299 
300  if(major_pos != std::string::npos){
301  size_t minor_pos = version.find('.', major_pos+1);
302  std::string minor_str = version.substr(major_pos+1, (minor_pos - (major_pos+1)));
303  minor = (unsigned)atoi(minor_str.c_str());
304 
305  if(minor_pos != std::string::npos){
306  std::string patch_str = version.substr(minor_pos+1);
307  patch = (unsigned)atoi(patch_str.c_str());
308  }
309  else{
310  patch = 0;
311  }
312  }
313  else{
314  minor = 0;
315  patch = 0;
316  }
317  }
318 }
319 
334 bool
335 vpIoTools::checkDirectory(const char *dirname )
336 {
337 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
338  struct stat stbuf;
339 #elif defined(_WIN32)
340  struct _stat stbuf;
341 #endif
342 
343  if ( dirname == NULL || dirname[0] == '\0' ) {
344  return false;
345  }
346 
347  std::string _dirname = path(dirname);
348 
349 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
350  if ( stat( _dirname.c_str(), &stbuf ) != 0 )
351 #elif defined(_WIN32)
352  if ( _stat( _dirname.c_str(), &stbuf ) != 0 )
353 #endif
354  {
355  return false;
356  }
357  if ( (stbuf.st_mode & S_IFDIR) == 0 ) {
358  return false;
359  }
360 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
361  if ( (stbuf.st_mode & S_IWUSR) == 0 )
362 #elif defined(_WIN32)
363  if ( (stbuf.st_mode & S_IWRITE) == 0 )
364 #endif
365  {
366  return false;
367  }
368  return true;
369 }
370 
384 bool
385 vpIoTools::checkDirectory(const std::string &dirname )
386 {
387  return vpIoTools::checkDirectory(dirname.c_str());
388 }
403 void
404 vpIoTools::makeDirectory(const char *dirname )
405 {
406 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
407  struct stat stbuf;
408 #elif defined(_WIN32)
409  struct _stat stbuf;
410 #endif
411 
412  if ( dirname == NULL || dirname[0] == '\0' ) {
413  vpERROR_TRACE( "invalid directory name\n");
415  "invalid directory name")) ;
416  }
417 
418  std::string _dirname = path(dirname);
419 
420 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
421  if ( stat( _dirname.c_str(), &stbuf ) != 0 )
422 #elif defined(_WIN32)
423  if ( _stat( _dirname.c_str(), &stbuf ) != 0 )
424 #endif
425  {
426 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__)))
427  if ( mkdir( _dirname.c_str(), (mode_t)0755 ) != 0 )
428 #elif defined(_WIN32)
429  if ( _mkdir( _dirname.c_str()) != 0 )
430 #endif
431  {
432  vpERROR_TRACE("unable to create directory '%s'\n", dirname );
434  "unable to create directory")) ;
435  }
436  vpDEBUG_TRACE(2,"has created directory '%s'\n", dirname );
437  }
438 
439  if ( checkDirectory( dirname ) == false) {
440  vpERROR_TRACE("unable to create directory '%s'\n", dirname );
442  "unable to create directory")) ;
443  }
444 }
445 
458 void
459 vpIoTools::makeDirectory(const std::string &dirname )
460 {
461  try {
462  vpIoTools::makeDirectory(dirname.c_str());
463  }
464  catch (...) {
465  vpERROR_TRACE("unable to create directory '%s'\n",dirname.c_str());
467  "unable to create directory")) ;
468  }
469 }
470 
484 bool
485 vpIoTools::checkFilename(const char *filename)
486 {
487 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
488  struct stat stbuf;
489 #elif defined(_WIN32)
490  struct _stat stbuf;
491 #endif
492 
493  if ( filename == NULL || filename[0] == '\0' ) {
494  return false;
495  }
496 
497  std::string _filename = path(filename);
498 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
499  if ( stat( _filename.c_str(), &stbuf ) != 0 )
500 #elif defined(_WIN32)
501  if ( _stat( _filename.c_str(), &stbuf ) != 0 )
502 #endif
503  {
504  return false;
505  }
506  if ( (stbuf.st_mode & S_IFREG) == 0 ) {
507  return false;
508  }
509 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
510  if ( (stbuf.st_mode & S_IRUSR) == 0 )
511 #elif defined(_WIN32)
512  if ( (stbuf.st_mode & S_IREAD) == 0 )
513 #endif
514  {
515  return false;
516  }
517  return true;
518 }
519 
532 bool
533 vpIoTools::checkFilename(const std::string &filename)
534 {
535  return vpIoTools::checkFilename(filename.c_str());
536 }
537 
550 bool
551 vpIoTools::copy(const char *src, const char *dst)
552 {
553  char cmd[FILENAME_MAX];
554  int ret;
555  // Check if we have to consider a file or a directory
556  if ( vpIoTools::checkFilename(src) ) {
557  //std::cout << "copy file: " << src << " in " << dst << std::endl;
558 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
559  sprintf(cmd, "cp -p %s %s", src, dst);
560 #elif defined(_WIN32)
561  std::string src_ = vpIoTools::path(src);
562  std::string dst_ = vpIoTools::path(dst);
563  sprintf(cmd, "copy %s %s", src_.c_str(), dst_.c_str());
564 #endif
565  ret = system( cmd );
566  //std::cout << cmd << " return value: " << ret << std::endl;
567  return true;
568  }
569  else if ( vpIoTools::checkDirectory(src) ) {
570  //std::cout << "copy directory: " << src << " in " << dst << std::endl;
571 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
572  sprintf(cmd, "cp -p -r %s %s", src, dst);
573 #elif defined(_WIN32)
574  std::string src_ = vpIoTools::path(src);
575  std::string dst_ = vpIoTools::path(dst);
576  sprintf(cmd, "copy %s %s", src_.c_str(), dst_.c_str());
577 #endif
578  ret = system( cmd );
579  if(ret) {}; // to avoid a warning
580  //std::cout << cmd << " return value: " << ret << std::endl;
581  return true;
582  }
583  else {
584  std::cout << "Cannot copy: " << src << " in " << dst << std::endl;
585  return false;
586  }
587 }
600 bool
601 vpIoTools::copy(const std::string &src, const std::string &dst)
602 {
603  return vpIoTools::copy(src.c_str(), dst.c_str());
604 }
605 
616 bool
617 vpIoTools::remove(const char *file_or_dir)
618 {
619  // Check if we have to consider a file or a directory
620  if ( vpIoTools::checkFilename(file_or_dir) ) {
621  //std::cout << "remove file: " << file_or_dir << std::endl;
622  if (::remove(file_or_dir) != 0)
623  return false;
624  else
625  return true;
626  }
627  else if ( vpIoTools::checkDirectory(file_or_dir) ) {
628  //std::cout << "remove directory: " << file_or_dir << std::endl;
629  char cmd[FILENAME_MAX];
630 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
631  sprintf(cmd, "rm -rf %s", file_or_dir);
632 #elif defined(_WIN32)
633  std::string file_or_dir_ = vpIoTools::path(file_or_dir);
634  sprintf(cmd, "rmdir /S /Q %s", file_or_dir_.c_str());
635 #endif
636  int ret = system( cmd );
637  if(ret) {}; // to avoid a warning
638  //std::cout << cmd << " return value: " << ret << std::endl;
639  return true;
640  }
641  else {
642  std::cout << "Cannot remove: " << file_or_dir << std::endl;
643  return false;
644  }
645 }
657 bool
658 vpIoTools::remove(const std::string &file_or_dir)
659 {
660  return vpIoTools::remove(file_or_dir.c_str());
661 }
662 
674 bool
675 vpIoTools::rename(const char *oldfilename, const char *newfilename)
676 {
677  if (::rename(oldfilename, newfilename) != 0)
678  return false;
679  else
680  return true;
681 }
682 
694 bool
695 vpIoTools::rename(const std::string &oldfilename, const std::string &newfilename)
696 {
697  return vpIoTools::rename(oldfilename.c_str(), newfilename.c_str());
698 }
699 
700 
701 
714 std::string
715 vpIoTools::path(const char *pathname)
716 {
717  std::string path(pathname);
718 
719 #if defined(_WIN32)
720  for(unsigned int i=0 ; i<path.length() ; i++)
721  if( path[i] == '/') path[i] = '\\';
722 #else
723  for(unsigned int i=0 ; i<path.length() ; i++)
724  if( path[i] == '\\') path[i] = '/';
725  wordexp_t exp_result;
726  wordexp(path.c_str(), &exp_result, 0);
727  path = std::string(exp_result.we_wordv[0]);
728  wordfree(&exp_result);
729 #endif
730 
731  return path;
732 }
733 
746 std::string
747 vpIoTools::path(const std::string &pathname)
748 {
749  return path(pathname.c_str());
750 }
751 
752 
760 bool vpIoTools::loadConfigFile(const std::string &confFile)
761 {
762  configFile = path(confFile);
763  configVars.clear();configValues.clear();
764  std::ifstream confContent(configFile.c_str(), std::ios::in);
765 
766  if(confContent.is_open())
767  {
768  std::string line,var,val;
769  long unsigned int k;
770  int c;
771  std::string stop[3] = {" ", "\t", "#"};
772  while(std::getline(confContent, line))
773  {
774  if((line.find("#",0,1) != 0) && (line.size() > 2))
775  {
776  try
777  {
778  // name of the variable
779  k = (unsigned long)line.find(" ");
780  var = line.substr(0,k);
781  // look for the end of the actual value
782  c = 200;
783  for(unsigned i=0;i<3;++i)
784  c = vpMath::minimum(c,(int)line.find(stop[i],k+1));
785  if(c==-1)
786  c = (int)line.size();
787  long unsigned int c_ = (long unsigned int) c;
788  val = line.substr(k+1,c_-k-1);
789  configVars.push_back(var);
790  configValues.push_back(val);
791  }
792  catch(...){}
793  }
794  }
795  confContent.close();
796  }
797  else {
798  return false;
799  }
800  return true;
801 }
802 
811 bool vpIoTools::readConfigVar(const std::string &var, float &value)
812 {
813  bool found = false;
814  for(unsigned int k=0;k<configVars.size() && found==false;++k)
815  {
816  if(configVars[k] == var)
817  {
818  if(configValues[k].compare("PI") == 0)
819  value = (float) M_PI;
820  else if(configValues[k].compare("PI/2") == 0)
821  value = (float) (M_PI/2.0);
822  else if(configValues[k].compare("-PI/2") == 0)
823  value = (float) (-M_PI/2.0);
824  else
825  value = (float) atof(configValues[k].c_str());
826  found = true;
827  }
828  }
829  if(found == false)
830  std::cout << var << " not found in config file" << std::endl;
831  return found;
832 }
841 bool vpIoTools::readConfigVar(const std::string &var, double &value)
842 {
843  bool found = false;
844  for(unsigned int k=0;k<configVars.size() && found==false;++k)
845  {
846  if(configVars[k] == var)
847  {
848  if(configValues[k].compare("PI") == 0)
849  value = M_PI;
850  else if(configValues[k].compare("PI/2") == 0)
851  value = M_PI/2;
852  else if(configValues[k].compare("-PI/2") == 0)
853  value = -M_PI/2;
854  else
855  value = atof(configValues[k].c_str());
856  found = true;
857  }
858  }
859  if(found == false)
860  std::cout << var << " not found in config file" << std::endl;
861  return found;
862 }
863 
872 bool vpIoTools::readConfigVar(const std::string &var, int &value)
873 {
874  bool found = false;
875  for(unsigned int k=0;k<configVars.size() && found==false;++k)
876  {
877  if(configVars[k] == var)
878  {
879  value = atoi(configValues[k].c_str());
880  found = true;
881  }
882  }
883  if(found == false)
884  std::cout << var << " not found in config file" << std::endl;
885  return found;
886 }
887 
896 bool vpIoTools::readConfigVar(const std::string &var, unsigned int &value)
897 {
898  int v = 0;
899  bool found = readConfigVar(var,v);
900  value = (unsigned int) v;
901  return found;
902 }
903 
912 bool vpIoTools::readConfigVar(const std::string &var, bool &value)
913 {
914  int v = 0;
915  bool found = readConfigVar(var,v);
916  value = (v!=0);
917  return found;
918 }
919 
928 bool vpIoTools::readConfigVar(const std::string &var, vpColor &value)
929 {
930  unsigned int v = 0;
931  bool found = readConfigVar(var,v);
932  value = vpColor::getColor(v);
933  return found;
934 }
935 
944 bool vpIoTools::readConfigVar(const std::string &var, std::string &value)
945 {
946  bool found = false;
947  for(unsigned int k=0;k<configVars.size() && found==false;++k)
948  {
949  if(configVars[k] == var)
950  {
951  value = configValues[k];
952  found = true;
953  }
954  }
955  if(found == false)
956  std::cout << var << " not found in config file" << std::endl;
957  return found;
958 }
959 
972 bool vpIoTools::readConfigVar(const std::string &var, vpArray2D<double> &value, const unsigned int &nCols, const unsigned int &nRows)
973 {
974  bool found = false;
975  std::string nb;
976  for(unsigned int k=0;k<configVars.size() && found==false;++k)
977  {
978  if(configVars[k] == var)
979  {
980  found = true;
981  // resize or not
982  if(nCols != 0 && nRows != 0)
983  value.resize(nRows, nCols);
984  size_t ind=0,ind2;
985  for(unsigned int i=0;i<value.getRows();++i)
986  for(unsigned int j=0;j<value.getCols();++j)
987  {
988  ind2 = configValues[k].find(",",ind);
989  nb = configValues[k].substr(ind,ind2-ind);
990  if(nb.compare("PI") == 0)
991  value[i][j] = M_PI;
992  else if(nb.compare("PI/2") == 0)
993  value[i][j] = M_PI/2;
994  else if(nb.compare("-PI/2") == 0)
995  value[i][j] = -M_PI/2;
996  else
997  value[i][j] = atof(nb.c_str());
998  ind = ind2+1;
999  }
1000  }
1001  }
1002  if(found == false)
1003  std::cout << var << " not found in config file" << std::endl;
1004  return found;
1005 }
1006 
1007 // construct experiment filename & path
1008 
1016 void vpIoTools::addNameElement(const std::string &strTrue, const bool &cond, const std::string &strFalse)
1017 {
1018  if(cond)
1019  baseName += "_" + strTrue;
1020  else if(strFalse != "")
1021  baseName += "_" + strFalse;
1022 }
1023 
1031 void vpIoTools::addNameElement(const std::string &strTrue, const double &val)
1032 {
1033  //if(val != 0.)
1034  if(std::fabs(val) < std::numeric_limits<double>::epsilon())
1035  {
1036  char valC[256];
1037  sprintf(valC, "%.3f", val);
1038  std::string valS(valC);
1039  baseName += "_" + strTrue + valS;
1040  }
1041 }
1042 
1051 void vpIoTools::createBaseNamePath(const bool &empty)
1052 {
1053  if(vpIoTools::checkDirectory(baseDir + baseName) == false) {
1055  std::cout << "creating directory " + baseDir + baseName << std::endl;
1056  }
1057  else {
1058  if(empty) {
1059  std::cout << "emptying directory " + baseDir + baseName << std::endl;
1061  }
1062  }
1063 }
1064 
1071 void vpIoTools::saveConfigFile(const bool &actuallySave)
1072 {
1073  if(actuallySave) {
1074  std::string dest = baseDir + "/" + baseName + "_config.txt";
1075  // file copy
1076  vpIoTools::copy(configFile, dest);
1077  }
1078 }
1079 
1092 {
1093  std::string data_path;
1094  std::string file_to_test("ViSP-images/mbt/cube.cao");
1095  std::string filename;
1096 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
1097  // Test if visp-images-data package is u-installed (Ubuntu and Debian)
1098  data_path = "/usr/share/visp-images-data";
1099  filename = data_path + "/" + file_to_test;
1100  if (vpIoTools::checkFilename(filename))
1101  return data_path;
1102 #endif
1103  // Test if VISP_INPUT_IMAGE_PATH env var is set
1104  try {
1105  data_path = vpIoTools::getenv("VISP_INPUT_IMAGE_PATH");
1106  filename = data_path + "/" + file_to_test;
1107  if (vpIoTools::checkFilename(filename))
1108  return data_path;
1109  }
1110  catch(...) {
1111  }
1112  data_path = "";
1113  return data_path;
1114 }
1115 
1125 std::string vpIoTools::getFileExtension(const std::string& pathname, const bool checkFile)
1126 {
1127  if(checkFile && (vpIoTools::checkDirectory(pathname) || !vpIoTools::checkFilename(pathname))) {
1128  return "";
1129  }
1130 
1131  //On Unix, or on the Mac
1132  std::string sep = "/";
1133  std::string altsep = "";
1134  std::string extsep = ".";
1135 
1136 #if defined(_WIN32)
1137  sep = "\\";
1138  altsep = "/";
1139  extsep = ".";
1140 #endif
1141 
1142  //Python 2.7.8 module.
1143 //# Split a path in root and extension.
1144 //# The extension is everything starting at the last dot in the last
1145 //# pathname component; the root is everything before that.
1146 //# It is always true that root + ext == p.
1147 //
1148 //# Generic implementation of splitext, to be parametrized with
1149 //# the separators
1150 //def _splitext(p, sep, altsep, extsep):
1151 // """Split the extension from a pathname.
1152 //
1153 // Extension is everything from the last dot to the end, ignoring
1154 // leading dots. Returns "(root, ext)"; ext may be empty."""
1155 //
1156 // sepIndex = p.rfind(sep)
1157 // if altsep:
1158 // altsepIndex = p.rfind(altsep)
1159 // sepIndex = max(sepIndex, altsepIndex)
1160 //
1161 // dotIndex = p.rfind(extsep)
1162 // if dotIndex > sepIndex:
1163 // # skip all leading dots
1164 // filenameIndex = sepIndex + 1
1165 // while filenameIndex < dotIndex:
1166 // if p[filenameIndex] != extsep:
1167 // return p[:dotIndex], p[dotIndex:]
1168 // filenameIndex += 1
1169 //
1170 // return p, ''
1171 
1172  int sepIndex = (int)pathname.rfind(sep);
1173  if(!altsep.empty()) {
1174  int altsepIndex = (int)pathname.rfind(altsep);
1175  sepIndex = (std::max)(sepIndex, altsepIndex);
1176  }
1177 
1178  size_t dotIndex = pathname.rfind(extsep);
1179  if(dotIndex != std::string::npos) {
1180  //The extsep character exists
1181  if((sepIndex != (int)std::string::npos && (int)dotIndex > sepIndex) || sepIndex == (int)std::string::npos) {
1182  if(sepIndex == (int)std::string::npos) {
1183  sepIndex = -1;
1184  }
1185  size_t filenameIndex = (size_t)(sepIndex + 1);
1186 
1187  while(filenameIndex < dotIndex) {
1188  if(pathname.compare(filenameIndex, 1, extsep) != 0) {
1189  return pathname.substr(dotIndex);
1190  }
1191  filenameIndex++;
1192  }
1193  }
1194  }
1195 
1196 
1197  return "";
1198 }
1199 
1205 std::string vpIoTools::getName(const std::string& pathname)
1206 {
1207  if(pathname.size() > 0)
1208  {
1209  std::string convertedPathname = vpIoTools::path(pathname);
1210 
1211  size_t index = convertedPathname.find_last_of(vpIoTools::separator);
1212  if(index != std::string::npos) {
1213  return convertedPathname.substr(index + 1);
1214  }
1215 
1216  return convertedPathname;
1217  }
1218 
1219  return "";
1220 }
1221 
1227 std::string vpIoTools::getNameWE(const std::string& pathname)
1228 {
1229  std::string name = vpIoTools::getName(pathname);
1230  size_t found = name.find_last_of(".");
1231  std::string name_we = name.substr(0, found);
1232  return name_we;
1233 }
1234 
1240 std::string vpIoTools::getParent(const std::string& pathname)
1241 {
1242  if(pathname.size() > 0)
1243  {
1244  std::string convertedPathname = vpIoTools::path(pathname);
1245 
1246  size_t index = convertedPathname.find_last_of(vpIoTools::separator);
1247  if(index != std::string::npos) {
1248  return convertedPathname.substr(0, index);
1249  }
1250  }
1251 
1252  return "";
1253 }
1254 
1265 std::string vpIoTools::createFilePath(const std::string& parent, const std::string child)
1266 {
1267  if(child.size() == 0 && parent.size() == 0)
1268  {
1269  return "";
1270  }
1271 
1272  if(child.size() == 0)
1273  {
1274  return vpIoTools::path(parent);
1275  }
1276 
1277  if(parent.size() == 0)
1278  {
1279  return vpIoTools::path(child);
1280  }
1281 
1282  std::string convertedParent = vpIoTools::path(parent);
1283  std::string convertedChild = vpIoTools::path(child);
1284 
1285  std::stringstream ss;
1286  ss << vpIoTools::separator;
1287  std::string stringSeparator;
1288  ss >> stringSeparator;
1289 
1290  std::string lastConvertedParentChar = convertedParent.substr(convertedParent.size() - 1);
1291  std::string firstConvertedChildChar = convertedChild.substr(0, 1);
1292 
1293  if(lastConvertedParentChar == stringSeparator)
1294  {
1295  convertedParent = convertedParent.substr(0, convertedParent.size() - 1);
1296  }
1297 
1298  if(firstConvertedChildChar == stringSeparator)
1299  {
1300  convertedChild = convertedChild.substr(1);
1301  }
1302 
1303  return std::string(convertedParent + vpIoTools::separator + convertedChild);
1304 }
1305 
1311 bool vpIoTools::isAbsolutePathname(const std::string& pathname)
1312 {
1313  //# Inspired by the Python 2.7.8 module.
1314  //# Return whether a path is absolute.
1315  //# Trivial in Posix, harder on the Mac or MS-DOS.
1316  //# For DOS it is absolute if it starts with a slash or backslash (current
1317  //# volume), or if a pathname after the volume letter and colon / UNC resource
1318  //# starts with a slash or backslash.
1319  //
1320  //def isabs(s):
1321  // """Test whether a path is absolute"""
1322  // s = splitdrive(s)[1]
1323  // return s != '' and s[:1] in '/\\'
1324  std::string path = splitDrive(pathname).second;
1325  return path.size() > 0 && (path.substr(0, 1) == "/" || path.substr(0, 1) == "\\");
1326 }
1327 
1335 std::pair<std::string, std::string> vpIoTools::splitDrive(const std::string& pathname)
1336 {
1337 //# Split a path in a drive specification (a drive letter followed by a
1338 //# colon) and the path specification.
1339 //# It is always true that drivespec + pathspec == p
1340 //def splitdrive(p):
1341 // """Split a pathname into drive/UNC sharepoint and relative path specifiers.
1342 // Returns a 2-tuple (drive_or_unc, path); either part may be empty.
1343 //
1344 // If you assign
1345 // result = splitdrive(p)
1346 // It is always true that:
1347 // result[0] + result[1] == p
1348 //
1349 // If the path contained a drive letter, drive_or_unc will contain everything
1350 // up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir")
1351 //
1352 // If the path contained a UNC path, the drive_or_unc will contain the host name
1353 // and share up to but not including the fourth directory separator character.
1354 // e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir")
1355 //
1356 // Paths cannot contain both a drive letter and a UNC path.
1357 //
1358 // """
1359 // if len(p) > 1:
1360 // normp = p.replace(altsep, sep)
1361 // if (normp[0:2] == sep*2) and (normp[2] != sep):
1362 // # is a UNC path:
1363 // # vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
1364 // # \\machine\mountpoint\directory\etc\...
1365 // # directory ^^^^^^^^^^^^^^^
1366 // index = normp.find(sep, 2)
1367 // if index == -1:
1368 // return '', p
1369 // index2 = normp.find(sep, index + 1)
1370 // # a UNC path can't have two slashes in a row
1371 // # (after the initial two)
1372 // if index2 == index + 1:
1373 // return '', p
1374 // if index2 == -1:
1375 // index2 = len(p)
1376 // return p[:index2], p[index2:]
1377 // if normp[1] == ':':
1378 // return p[:2], p[2:]
1379 // return '', p
1380 
1381 
1382  //On Unix, the drive is always empty.
1383  //On the Mac, the drive is always empty (don't use the volume name -- it doesn't have the same
1384  //syntactic and semantic oddities as DOS drive letters, such as there being a separate current directory per drive).
1385 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__)))
1386  return std::pair<std::string, std::string>("", pathname);
1387 #else
1388  const std::string sep = "\\";
1389  const std::string sepsep = "\\\\";
1390  const std::string altsep = "/";
1391 
1392  if(pathname.size() > 1) {
1393  std::string normPathname = pathname;
1394  std::replace(normPathname.begin(), normPathname.end(), *altsep.c_str(), *sep.c_str());
1395 
1396  if(normPathname.substr(0, 2) == sepsep && normPathname.substr(2, 1) != sep) {
1397  // is a UNC path:
1398  // vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
1399  // \\machine\mountpoint\directory\etc\...
1400  // directory ^^^^^^^^^^^^^^^
1401  size_t index = normPathname.find(sep, 2);
1402  if(index == std::string::npos) {
1403  return std::pair<std::string, std::string>("", pathname);
1404  }
1405 
1406  size_t index2 = normPathname.find(sep, index + 1);
1407  //# a UNC path can't have two slashes in a row
1408  //# (after the initial two)
1409  if(index2 == index + 1) {
1410  return std::pair<std::string, std::string>("", pathname);
1411  }
1412 
1413  if(index2 == std::string::npos) {
1414  index2 = pathname.size();
1415  }
1416 
1417  return std::pair<std::string, std::string>(pathname.substr(0, index2), pathname.substr(index2));
1418  }
1419 
1420  if(normPathname[1] == ':') {
1421  return std::pair<std::string, std::string>(pathname.substr(0, 2), pathname.substr(2));
1422  }
1423  }
1424 
1425  return std::pair<std::string, std::string>("", pathname);
1426 #endif
1427 }
1428 
1477 std::vector<std::string> vpIoTools::splitChain(const std::string & chain, const std::string & sep)
1478 {
1479  size_t startIndex = 0;
1480 
1481  std::string chainToSplit = chain;
1482  std::vector<std::string> subChain;
1483  size_t sepIndex = chainToSplit.find(sep);
1484 
1485  while(sepIndex != std::string::npos) {
1486 
1487  subChain.push_back( chainToSplit.substr(startIndex, sepIndex) );
1488  chainToSplit = chainToSplit.substr(sepIndex+1, chain.size()-1);
1489 
1490  sepIndex = chainToSplit.find(sep);
1491  }
1492  subChain.push_back(chainToSplit);
1493 
1494  return subChain;
1495 }
static bool remove(const char *filename)
Definition: vpIoTools.cpp:617
static bool checkDirectory(const char *dirname)
Definition: vpIoTools.cpp:335
static std::string getViSPImagesDataPath()
Definition: vpIoTools.cpp:1091
void resize(const unsigned int nrows, const unsigned int ncols, const bool flagNullify=true)
Definition: vpArray2D.h:167
static bool isAbsolutePathname(const std::string &pathname)
Definition: vpIoTools.cpp:1311
static void getVersion(const std::string &version, unsigned int &major, unsigned int &minor, unsigned int &patch)
Definition: vpIoTools.cpp:288
static std::string getFileExtension(const std::string &pathname, const bool checkFile=false)
Definition: vpIoTools.cpp:1125
#define vpERROR_TRACE
Definition: vpDebug.h:391
Class to define colors available for display functionnalities.
Definition: vpColor.h:121
static const char separator
Definition: vpIoTools.h:180
static std::string getenv(const char *env)
Definition: vpIoTools.cpp:224
static bool rename(const char *oldfilename, const char *newfilename)
Definition: vpIoTools.cpp:675
static std::string path(const char *pathname)
Definition: vpIoTools.cpp:715
Error that can be emited by the vpIoTools class and its derivates.
Definition: vpIoException.h:68
unsigned int getCols() const
Return the number of columns of the 2D array.
Definition: vpArray2D.h:154
static std::string getParent(const std::string &pathname)
Definition: vpIoTools.cpp:1240
static void createBaseNamePath(const bool &empty=false)
Definition: vpIoTools.cpp:1051
static std::string baseDir
Definition: vpIoTools.h:230
static void makeDirectory(const char *dirname)
Definition: vpIoTools.cpp:404
static bool checkFilename(const char *filename)
Definition: vpIoTools.cpp:485
static void setBaseName(const std::string &s)
Definition: vpIoTools.cpp:76
static std::string createFilePath(const std::string &parent, const std::string child)
Definition: vpIoTools.cpp:1265
static bool copy(const char *src, const char *dst)
Definition: vpIoTools.cpp:551
static std::pair< std::string, std::string > splitDrive(const std::string &pathname)
Definition: vpIoTools.cpp:1335
static std::string getUserName()
Definition: vpIoTools.cpp:161
static std::vector< std::string > splitChain(const std::string &chain, const std::string &sep)
Definition: vpIoTools.cpp:1477
static Type minimum(const Type &a, const Type &b)
Definition: vpMath.h:152
unsigned int getRows() const
Return the number of rows of the 2D array.
Definition: vpArray2D.h:152
static void saveConfigFile(const bool &actuallySave=true)
Definition: vpIoTools.cpp:1071
static std::vector< std::string > configVars
Definition: vpIoTools.h:232
static std::string getName(const std::string &pathname)
Definition: vpIoTools.cpp:1205
static std::string baseName
Definition: vpIoTools.h:229
static std::string getFullName()
Definition: vpIoTools.cpp:94
static std::string configFile
Definition: vpIoTools.h:231
static void setBaseDir(const std::string &dir)
Definition: vpIoTools.cpp:82
static std::string getNameWE(const std::string &pathname)
Definition: vpIoTools.cpp:1227
static std::string getBaseName()
Definition: vpIoTools.cpp:88
#define vpDEBUG_TRACE
Definition: vpDebug.h:478
static vpColor getColor(const unsigned int &i)
Definition: vpColor.h:234
static bool readConfigVar(const std::string &var, float &value)
Definition: vpIoTools.cpp:811
static std::vector< std::string > configValues
Definition: vpIoTools.h:233
static bool loadConfigFile(const std::string &confFile)
Definition: vpIoTools.cpp:760
static void addNameElement(const std::string &strTrue, const bool &cond=true, const std::string &strFalse="")
Definition: vpIoTools.cpp:1016