ViSP  2.10.0
vpIoTools.cpp
1 /****************************************************************************
2  *
3  * $Id: vpIoTools.cpp 5214 2015-01-27 18:33:01Z fspindle $
4  *
5  * This file is part of the ViSP software.
6  * Copyright (C) 2005 - 2014 by INRIA. All rights reserved.
7  *
8  * This software is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * ("GPL") version 2 as published by the Free Software Foundation.
11  * See the file LICENSE.txt at the root directory of this source
12  * distribution for additional information about the GNU GPL.
13  *
14  * For using ViSP with software that can not be combined with the GNU
15  * GPL, please contact INRIA about acquiring a ViSP Professional
16  * Edition License.
17  *
18  * See http://www.irisa.fr/lagadic/visp/visp.html for more information.
19  *
20  * This software was developed at:
21  * INRIA Rennes - Bretagne Atlantique
22  * Campus Universitaire de Beaulieu
23  * 35042 Rennes Cedex
24  * France
25  * http://www.irisa.fr/lagadic
26  *
27  * If you have questions regarding the use of this file, please contact
28  * INRIA at visp@inria.fr
29  *
30  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
31  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
32  *
33  *
34  * Description:
35  * Directory management.
36  *
37  * Authors:
38  * Fabien Spindler
39  *
40  *****************************************************************************/
41 
46 #include <visp/vpIoTools.h>
47 #include <visp/vpDebug.h>
48 #include <visp/vpIoException.h>
49 #include <stdlib.h>
50 #include <stdio.h>
51 #include <fstream>
52 #include <string.h>
53 #include <sys/stat.h>
54 #include <sys/types.h>
55 #include <fcntl.h>
56 #include <limits>
57 #include <cmath>
58 #include <algorithm>
59 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
60 # include <unistd.h>
61 #elif defined(_WIN32)
62 # include <windows.h>
63 # include <direct.h>
64 #endif
65 #if !defined(_WIN32)
66 # include <wordexp.h>
67 #endif
68 
69 std::string vpIoTools::baseName = "";
70 std::string vpIoTools::baseDir = "";
71 std::string vpIoTools::configFile = "";
72 std::vector<std::string> vpIoTools::configVars = std::vector<std::string>();
73 std::vector<std::string> vpIoTools::configValues = std::vector<std::string>();
74 
75 
93 void
94 vpIoTools::getUserName(std::string &username)
95 {
96  // With MinGW, UNIX and _WIN32 are defined
97 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
98  // Get the user name.
99  char *_username = NULL;
100  _username = ::getenv("LOGNAME");
101  if (_username == NULL) {
102  vpERROR_TRACE( "Cannot get the username. Check your LOGNAME environment variable" );
104  "Cannot get the username")) ;
105  }
106  username = _username;
107 #elif defined(_WIN32)
108  unsigned int info_buffer_size = 1024;
109  TCHAR *infoBuf = new TCHAR [info_buffer_size];
110  DWORD bufCharCount = (DWORD) info_buffer_size;
111  // Get the user name.
112  if( ! GetUserName( infoBuf, &bufCharCount ) ) {
113  delete [] infoBuf;
114  vpERROR_TRACE( "Cannot get the username" );
116  "Cannot get the username")) ;
117 
118  }
119  username = infoBuf;
120  delete [] infoBuf;
121 #endif
122 }
140 std::string
142 {
143  std::string username;
144 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
145  // Get the user name.
146  char *_username = NULL;
147  _username = ::getenv("LOGNAME");
148  if (_username == NULL) {
149  vpERROR_TRACE( "Cannot get the username. Check your LOGNAME environment variable" );
151  "Cannot get the username")) ;
152  }
153  username = _username;
154 #elif defined(_WIN32)
155  unsigned int info_buffer_size = 1024;
156  TCHAR *infoBuf = new TCHAR [info_buffer_size];
157  DWORD bufCharCount = (DWORD) info_buffer_size;
158  // Get the user name.
159  if( ! GetUserName( infoBuf, &bufCharCount ) ) {
160  delete [] infoBuf;
161  vpERROR_TRACE( "Cannot get the username" );
163  "Cannot get the username")) ;
164 
165  }
166  username = infoBuf;
167  delete [] infoBuf;
168 #endif
169  return username;
170 }
171 
203 std::string
204 vpIoTools::getenv(const char *env)
205 {
206  std::string value;
207  // Get the environment variable value.
208  char *_value = NULL;
209  _value = ::getenv(env);
210  if (_value == NULL) {
211  vpERROR_TRACE( "Cannot get the environment variable value" );
213  "Cannot get the environment variable value")) ;
214  }
215  value = _value;
216 
217  return value;
218 }
219 
252 std::string
253 vpIoTools::getenv(const std::string &env)
254 {
255  return (vpIoTools::getenv(env.c_str()));
256 }
257 
267 void
268 vpIoTools::getVersion(const std::string &version, unsigned int &major, unsigned int &minor, unsigned int &patch)
269 {
270  if(version.size() == 0){
271  major = 0;
272  minor = 0;
273  patch = 0;
274  }
275  else{
276  size_t major_pos = version.find('.');
277  std::string major_str = version.substr(0, major_pos);
278  major = (unsigned)atoi(major_str.c_str());
279 
280  if(major_pos != std::string::npos){
281  size_t minor_pos = version.find('.', major_pos+1);
282  std::string minor_str = version.substr(major_pos+1, (minor_pos - (major_pos+1)));
283  minor = (unsigned)atoi(minor_str.c_str());
284 
285  if(minor_pos != std::string::npos){
286  std::string patch_str = version.substr(minor_pos+1);
287  patch = (unsigned)atoi(patch_str.c_str());
288  }
289  else{
290  patch = 0;
291  }
292  }
293  else{
294  minor = 0;
295  patch = 0;
296  }
297  }
298 }
299 
314 bool
315 vpIoTools::checkDirectory(const char *dirname )
316 {
317 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
318  struct stat stbuf;
319 #elif defined(_WIN32)
320  struct _stat stbuf;
321 #endif
322 
323  if ( dirname == NULL || dirname[0] == '\0' ) {
324  return false;
325  }
326 
327  std::string _dirname = path(dirname);
328 
329 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
330  if ( stat( _dirname.c_str(), &stbuf ) != 0 )
331 #elif defined(_WIN32)
332  if ( _stat( _dirname.c_str(), &stbuf ) != 0 )
333 #endif
334  {
335  return false;
336  }
337  if ( (stbuf.st_mode & S_IFDIR) == 0 ) {
338  return false;
339  }
340 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
341  if ( (stbuf.st_mode & S_IWUSR) == 0 )
342 #elif defined(_WIN32)
343  if ( (stbuf.st_mode & S_IWRITE) == 0 )
344 #endif
345  {
346  return false;
347  }
348  return true;
349 }
350 
364 bool
365 vpIoTools::checkDirectory(const std::string &dirname )
366 {
367  return vpIoTools::checkDirectory(dirname.c_str());
368 }
383 void
384 vpIoTools::makeDirectory(const char *dirname )
385 {
386 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
387  struct stat stbuf;
388 #elif defined(_WIN32)
389  struct _stat stbuf;
390 #endif
391 
392  if ( dirname == NULL || dirname[0] == '\0' ) {
393  vpERROR_TRACE( "invalid directory name\n");
395  "invalid directory name")) ;
396  }
397 
398  std::string _dirname = path(dirname);
399 
400 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
401  if ( stat( _dirname.c_str(), &stbuf ) != 0 )
402 #elif defined(_WIN32)
403  if ( _stat( _dirname.c_str(), &stbuf ) != 0 )
404 #endif
405  {
406 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__)))
407  if ( mkdir( _dirname.c_str(), (mode_t)0755 ) != 0 )
408 #elif defined(_WIN32)
409  if ( _mkdir( _dirname.c_str()) != 0 )
410 #endif
411  {
412  vpERROR_TRACE("unable to create directory '%s'\n", dirname );
414  "unable to create directory")) ;
415  }
416  vpDEBUG_TRACE(2,"has created directory '%s'\n", dirname );
417  }
418 
419  if ( checkDirectory( dirname ) == false) {
420  vpERROR_TRACE("unable to create directory '%s'\n", dirname );
422  "unable to create directory")) ;
423  }
424 }
425 
438 void
439 vpIoTools::makeDirectory(const std::string &dirname )
440 {
441  try {
442  vpIoTools::makeDirectory(dirname.c_str());
443  }
444  catch (...) {
445  vpERROR_TRACE("unable to create directory '%s'\n",dirname.c_str());
447  "unable to create directory")) ;
448  }
449 }
450 
464 bool
465 vpIoTools::checkFilename(const char *filename)
466 {
467 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
468  struct stat stbuf;
469 #elif defined(_WIN32)
470  struct _stat stbuf;
471 #endif
472 
473  if ( filename == NULL || filename[0] == '\0' ) {
474  return false;
475  }
476 
477  std::string _filename = path(filename);
478 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
479  if ( stat( _filename.c_str(), &stbuf ) != 0 )
480 #elif defined(_WIN32)
481  if ( _stat( _filename.c_str(), &stbuf ) != 0 )
482 #endif
483  {
484  return false;
485  }
486  if ( (stbuf.st_mode & S_IFREG) == 0 ) {
487  return false;
488  }
489 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
490  if ( (stbuf.st_mode & S_IRUSR) == 0 )
491 #elif defined(_WIN32)
492  if ( (stbuf.st_mode & S_IREAD) == 0 )
493 #endif
494  {
495  return false;
496  }
497  return true;
498 }
499 
512 bool
513 vpIoTools::checkFilename(const std::string &filename)
514 {
515  return vpIoTools::checkFilename(filename.c_str());
516 }
517 
530 bool
531 vpIoTools::copy(const char *src, const char *dst)
532 {
533  char cmd[FILENAME_MAX];
534  int ret;
535  // Check if we have to consider a file or a directory
536  if ( vpIoTools::checkFilename(src) ) {
537  //std::cout << "copy file: " << src << " in " << dst << std::endl;
538 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
539  sprintf(cmd, "cp -p %s %s", src, dst);
540 #elif defined(_WIN32)
541  std::string src_ = vpIoTools::path(src);
542  std::string dst_ = vpIoTools::path(dst);
543  sprintf(cmd, "copy %s %s", src_.c_str(), dst_.c_str());
544 #endif
545  ret = system( cmd );
546  //std::cout << cmd << " return value: " << ret << std::endl;
547  return true;
548  }
549  else if ( vpIoTools::checkDirectory(src) ) {
550  //std::cout << "copy directory: " << src << " in " << dst << std::endl;
551 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
552  sprintf(cmd, "cp -p -r %s %s", src, dst);
553 #elif defined(_WIN32)
554  std::string src_ = vpIoTools::path(src);
555  std::string dst_ = vpIoTools::path(dst);
556  sprintf(cmd, "copy %s %s", src_.c_str(), dst_.c_str());
557 #endif
558  ret = system( cmd );
559  if(ret) {}; // to avoid a warning
560  //std::cout << cmd << " return value: " << ret << std::endl;
561  return true;
562  }
563  else {
564  std::cout << "Cannot copy: " << src << " in " << dst << std::endl;
565  return false;
566  }
567 }
580 bool
581 vpIoTools::copy(const std::string &src, const std::string &dst)
582 {
583  return vpIoTools::copy(src.c_str(), dst.c_str());
584 }
585 
596 bool
597 vpIoTools::remove(const char *file_or_dir)
598 {
599  // Check if we have to consider a file or a directory
600  if ( vpIoTools::checkFilename(file_or_dir) ) {
601  //std::cout << "remove file: " << file_or_dir << std::endl;
602  if (::remove(file_or_dir) != 0)
603  return false;
604  else
605  return true;
606  }
607  else if ( vpIoTools::checkDirectory(file_or_dir) ) {
608  //std::cout << "remove directory: " << file_or_dir << std::endl;
609  char cmd[FILENAME_MAX];
610 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
611  sprintf(cmd, "rm -rf %s", file_or_dir);
612 #elif defined(_WIN32)
613  std::string file_or_dir_ = vpIoTools::path(file_or_dir);
614  sprintf(cmd, "rmdir /S /Q %s", file_or_dir_.c_str());
615 #endif
616  int ret = system( cmd );
617  if(ret) {}; // to avoid a warning
618  //std::cout << cmd << " return value: " << ret << std::endl;
619  return true;
620  }
621  else {
622  std::cout << "Cannot remove: " << file_or_dir << std::endl;
623  return false;
624  }
625 }
637 bool
638 vpIoTools::remove(const std::string &file_or_dir)
639 {
640  return vpIoTools::remove(file_or_dir.c_str());
641 }
642 
654 bool
655 vpIoTools::rename(const char *oldfilename, const char *newfilename)
656 {
657  if (::rename(oldfilename, newfilename) != 0)
658  return false;
659  else
660  return true;
661 }
662 
674 bool
675 vpIoTools::rename(const std::string &oldfilename, const std::string &newfilename)
676 {
677  return vpIoTools::rename(oldfilename.c_str(), newfilename.c_str());
678 }
679 
680 
681 
694 std::string
695 vpIoTools::path(const char *pathname)
696 {
697  std::string path(pathname);
698 
699 #if defined(_WIN32)
700  for(unsigned int i=0 ; i<path.length() ; i++)
701  if( path[i] == '/') path[i] = '\\';
702 #else
703  for(unsigned int i=0 ; i<path.length() ; i++)
704  if( path[i] == '\\') path[i] = '/';
705  wordexp_t exp_result;
706  wordexp(path.c_str(), &exp_result, 0);
707  path = std::string(exp_result.we_wordv[0]);
708  wordfree(&exp_result);
709 #endif
710 
711  return path;
712 }
713 
726 std::string
727 vpIoTools::path(const std::string &pathname)
728 {
729  return path(pathname.c_str());
730 }
731 
732 
740 bool vpIoTools::loadConfigFile(const std::string &confFile)
741 {
742  configFile = path(confFile);
743  configVars.clear();configValues.clear();
744  std::ifstream confContent(configFile.c_str(), std::ios::in);
745 
746  if(confContent.is_open())
747  {
748  std::string line,var,val;
749  long unsigned int k;
750  int c;
751  std::string stop[3] = {" ", "\t", "#"};
752  while(std::getline(confContent, line))
753  {
754  if((line.find("#",0,1) != 0) && (line.size() > 2))
755  {
756  try
757  {
758  // name of the variable
759  k = (unsigned long)line.find(" ");
760  var = line.substr(0,k);
761  // look for the end of the actual value
762  c = 200;
763  for(unsigned i=0;i<3;++i)
764  c = vpMath::minimum(c,(int)line.find(stop[i],k+1));
765  if(c==-1)
766  c = (int)line.size();
767  long unsigned int c_ = (long unsigned int) c;
768  val = line.substr(k+1,c_-k-1);
769  configVars.push_back(var);
770  configValues.push_back(val);
771  }
772  catch(...){}
773  }
774  }
775  confContent.close();
776  }
777  else {
778  return false;
779  }
780  return true;
781 }
782 
791 bool vpIoTools::readConfigVar(const std::string &var, float &value)
792 {
793  bool found = false;
794  for(unsigned int k=0;k<configVars.size() && found==false;++k)
795  {
796  if(configVars[k] == var)
797  {
798  if(configValues[k].compare("PI") == 0)
799  value = M_PI;
800  else if(configValues[k].compare("PI/2") == 0)
801  value = M_PI/2;
802  else if(configValues[k].compare("-PI/2") == 0)
803  value = -M_PI/2;
804  else
805  value = (float) atof(configValues[k].c_str());
806  found = true;
807  }
808  }
809  if(found == false)
810  std::cout << var << " not found in config file" << std::endl;
811  return found;
812 }
821 bool vpIoTools::readConfigVar(const std::string &var, double &value)
822 {
823  bool found = false;
824  for(unsigned int k=0;k<configVars.size() && found==false;++k)
825  {
826  if(configVars[k] == var)
827  {
828  if(configValues[k].compare("PI") == 0)
829  value = M_PI;
830  else if(configValues[k].compare("PI/2") == 0)
831  value = M_PI/2;
832  else if(configValues[k].compare("-PI/2") == 0)
833  value = -M_PI/2;
834  else
835  value = atof(configValues[k].c_str());
836  found = true;
837  }
838  }
839  if(found == false)
840  std::cout << var << " not found in config file" << std::endl;
841  return found;
842 }
843 
852 bool vpIoTools::readConfigVar(const std::string &var, int &value)
853 {
854  bool found = false;
855  for(unsigned int k=0;k<configVars.size() && found==false;++k)
856  {
857  if(configVars[k] == var)
858  {
859  value = atoi(configValues[k].c_str());
860  found = true;
861  }
862  }
863  if(found == false)
864  std::cout << var << " not found in config file" << std::endl;
865  return found;
866 }
867 
876 bool vpIoTools::readConfigVar(const std::string &var, unsigned int &value)
877 {
878  int v = 0;
879  bool found = readConfigVar(var,v);
880  value = (unsigned int) v;
881  return found;
882 }
883 
892 bool vpIoTools::readConfigVar(const std::string &var, bool &value)
893 {
894  int v = 0;
895  bool found = readConfigVar(var,v);
896  value = (v!=0);
897  return found;
898 }
899 
908 bool vpIoTools::readConfigVar(const std::string &var, vpColor &value)
909 {
910  unsigned int v = 0;
911  bool found = readConfigVar(var,v);
912  value = vpColor::getColor(v);
913  return found;
914 }
915 
924 bool vpIoTools::readConfigVar(const std::string &var, std::string &value)
925 {
926  bool found = false;
927  for(unsigned int k=0;k<configVars.size() && found==false;++k)
928  {
929  if(configVars[k] == var)
930  {
931  value = configValues[k];
932  found = true;
933  }
934  }
935  if(found == false)
936  std::cout << var << " not found in config file" << std::endl;
937  return found;
938 }
939 
952 bool vpIoTools::readConfigVar(const std::string &var, vpMatrix &value, const unsigned int &nCols, const unsigned int &nRows)
953 {
954  bool found = false;
955  std::string nb;
956  for(unsigned int k=0;k<configVars.size() && found==false;++k)
957  {
958  if(configVars[k] == var)
959  {
960  found = true;
961  // resize or not
962  if(nCols != 0 && nRows != 0)
963  value.resize(nRows, nCols);
964  size_t ind=0,ind2;
965  for(unsigned int i=0;i<value.getRows();++i)
966  for(unsigned int j=0;j<value.getCols();++j)
967  {
968  ind2 = configValues[k].find(",",ind);
969  nb = configValues[k].substr(ind,ind2-ind);
970  if(nb.compare("PI") == 0)
971  value[i][j] = M_PI;
972  else if(nb.compare("PI/2") == 0)
973  value[i][j] = M_PI/2;
974  else if(nb.compare("-PI/2") == 0)
975  value[i][j] = -M_PI/2;
976  else
977  value[i][j] = atof(nb.c_str());
978  ind = ind2+1;
979  }
980  }
981  }
982  if(found == false)
983  std::cout << var << " not found in config file" << std::endl;
984  return found;
985 }
986 
987 // construct experiment filename & path
988 
996 void vpIoTools::addNameElement(const std::string &strTrue, const bool &cond, const std::string &strFalse)
997 {
998  if(cond)
999  baseName += "_" + strTrue;
1000  else if(strFalse != "")
1001  baseName += "_" + strFalse;
1002 }
1003 
1011 void vpIoTools::addNameElement(const std::string &strTrue, const double &val)
1012 {
1013  //if(val != 0.)
1014  if(std::fabs(val) < std::numeric_limits<double>::epsilon())
1015  {
1016  char valC[256];
1017  sprintf(valC, "%.3f", val);
1018  std::string valS(valC);
1019  baseName += "_" + strTrue + valS;
1020  }
1021 }
1022 
1031 void vpIoTools::createBaseNamePath(const bool &empty)
1032 {
1033  if(vpIoTools::checkDirectory(baseDir + baseName) == false) {
1035  std::cout << "creating directory " + baseDir + baseName << std::endl;
1036  }
1037  else {
1038  if(empty) {
1039  std::cout << "emptying directory " + baseDir + baseName << std::endl;
1041  }
1042  }
1043 }
1044 
1051 void vpIoTools::saveConfigFile(const bool &actuallySave)
1052 {
1053  if(actuallySave) {
1054  std::string dest = baseDir + "/" + baseName + "_config.txt";
1055  // file copy
1056  vpIoTools::copy(configFile, dest);
1057  }
1058 }
1059 
1072 {
1073  std::string data_path;
1074  std::string file_to_test("ViSP-images/mbt/cube.cao");
1075  std::string filename;
1076 #ifdef UNIX
1077  // Test if visp-images-data package is u-installed (Ubuntu and Debian)
1078  data_path = "/usr/share/visp-images-data";
1079  filename = data_path + "/" + file_to_test;
1080  if (vpIoTools::checkFilename(filename))
1081  return data_path;
1082 #endif
1083  // Test if VISP_INPUT_IMAGE_PATH env var is set
1084  try {
1085  data_path = vpIoTools::getenv("VISP_INPUT_IMAGE_PATH");
1086  filename = data_path + "/" + file_to_test;
1087  if (vpIoTools::checkFilename(filename))
1088  return data_path;
1089  }
1090  catch(...) {
1091  }
1092  data_path = "";
1093  return data_path;
1094 }
1095 
1105 std::string vpIoTools::getFileExtension(const std::string& pathname, const bool checkFile)
1106 {
1107  if(checkFile && (vpIoTools::checkDirectory(pathname) || !vpIoTools::checkFilename(pathname))) {
1108  return "";
1109  }
1110 
1111  //On Unix, or on the Mac
1112  std::string sep = "/";
1113  std::string altsep = "";
1114  std::string extsep = ".";
1115 
1116 #if defined(_WIN32)
1117  sep = "\\";
1118  altsep = "/";
1119  extsep = ".";
1120 #endif
1121 
1122  //Python 2.7.8 module.
1123 //# Split a path in root and extension.
1124 //# The extension is everything starting at the last dot in the last
1125 //# pathname component; the root is everything before that.
1126 //# It is always true that root + ext == p.
1127 //
1128 //# Generic implementation of splitext, to be parametrized with
1129 //# the separators
1130 //def _splitext(p, sep, altsep, extsep):
1131 // """Split the extension from a pathname.
1132 //
1133 // Extension is everything from the last dot to the end, ignoring
1134 // leading dots. Returns "(root, ext)"; ext may be empty."""
1135 //
1136 // sepIndex = p.rfind(sep)
1137 // if altsep:
1138 // altsepIndex = p.rfind(altsep)
1139 // sepIndex = max(sepIndex, altsepIndex)
1140 //
1141 // dotIndex = p.rfind(extsep)
1142 // if dotIndex > sepIndex:
1143 // # skip all leading dots
1144 // filenameIndex = sepIndex + 1
1145 // while filenameIndex < dotIndex:
1146 // if p[filenameIndex] != extsep:
1147 // return p[:dotIndex], p[dotIndex:]
1148 // filenameIndex += 1
1149 //
1150 // return p, ''
1151 
1152  int sepIndex = (int)pathname.rfind(sep);
1153  if(!altsep.empty()) {
1154  int altsepIndex = (int)pathname.rfind(altsep);
1155  sepIndex = (std::max)(sepIndex, altsepIndex);
1156  }
1157 
1158  size_t dotIndex = pathname.rfind(extsep);
1159  if(dotIndex != std::string::npos) {
1160  //The extsep character exists
1161  if((sepIndex != (int)std::string::npos && (int)dotIndex > sepIndex) || sepIndex == (int)std::string::npos) {
1162  if(sepIndex == (int)std::string::npos) {
1163  sepIndex = -1;
1164  }
1165  size_t filenameIndex = (size_t)(sepIndex + 1);
1166 
1167  while(filenameIndex < dotIndex) {
1168  if(pathname.compare(filenameIndex, 1, extsep) != 0) {
1169  return pathname.substr(dotIndex);
1170  }
1171  filenameIndex++;
1172  }
1173  }
1174  }
1175 
1176 
1177  return "";
1178 }
1179 
1185 std::string vpIoTools::getName(const std::string& pathname)
1186 {
1187  if(pathname.size() > 0)
1188  {
1189  std::string convertedPathname = vpIoTools::path(pathname);
1190 
1191  size_t index = convertedPathname.find_last_of(vpIoTools::separator);
1192  if(index != std::string::npos) {
1193  return convertedPathname.substr(index + 1);
1194  }
1195 
1196  return convertedPathname;
1197  }
1198 
1199  return "";
1200 }
1201 
1207 std::string vpIoTools::getNameWE(const std::string& pathname)
1208 {
1209  std::string name = vpIoTools::getName(pathname);
1210  size_t found = name.find_last_of(".");
1211  std::string name_we = name.substr(0, found);
1212  return name_we;
1213 }
1214 
1220 std::string vpIoTools::getParent(const std::string& pathname)
1221 {
1222  if(pathname.size() > 0)
1223  {
1224  std::string convertedPathname = vpIoTools::path(pathname);
1225 
1226  size_t index = convertedPathname.find_last_of(vpIoTools::separator);
1227  if(index != std::string::npos) {
1228  return convertedPathname.substr(0, index);
1229  }
1230  }
1231 
1232  return "";
1233 }
1234 
1245 std::string vpIoTools::createFilePath(const std::string& parent, const std::string child)
1246 {
1247  if(child.size() == 0 && parent.size() == 0)
1248  {
1249  return "";
1250  }
1251 
1252  if(child.size() == 0)
1253  {
1254  return vpIoTools::path(parent);
1255  }
1256 
1257  if(parent.size() == 0)
1258  {
1259  return vpIoTools::path(child);
1260  }
1261 
1262  std::string convertedParent = vpIoTools::path(parent);
1263  std::string convertedChild = vpIoTools::path(child);
1264 
1265  std::stringstream ss;
1266  ss << vpIoTools::separator;
1267  std::string stringSeparator;
1268  ss >> stringSeparator;
1269 
1270  std::string lastConvertedParentChar = convertedParent.substr(convertedParent.size() - 1);
1271  std::string firstConvertedChildChar = convertedChild.substr(0, 1);
1272 
1273  if(lastConvertedParentChar == stringSeparator)
1274  {
1275  convertedParent = convertedParent.substr(0, convertedParent.size() - 1);
1276  }
1277 
1278  if(firstConvertedChildChar == stringSeparator)
1279  {
1280  convertedChild = convertedChild.substr(1);
1281  }
1282 
1283  return std::string(convertedParent + vpIoTools::separator + convertedChild);
1284 }
1285 
1291 bool vpIoTools::isAbsolutePathname(const std::string& pathname)
1292 {
1293  //# Inspired by the Python 2.7.8 module.
1294  //# Return whether a path is absolute.
1295  //# Trivial in Posix, harder on the Mac or MS-DOS.
1296  //# For DOS it is absolute if it starts with a slash or backslash (current
1297  //# volume), or if a pathname after the volume letter and colon / UNC resource
1298  //# starts with a slash or backslash.
1299  //
1300  //def isabs(s):
1301  // """Test whether a path is absolute"""
1302  // s = splitdrive(s)[1]
1303  // return s != '' and s[:1] in '/\\'
1304  std::string path = splitDrive(pathname).second;
1305  return path.size() > 0 && (path.substr(0, 1) == "/" || path.substr(0, 1) == "\\");
1306 }
1307 
1315 std::pair<std::string, std::string> vpIoTools::splitDrive(const std::string& pathname)
1316 {
1317 //# Split a path in a drive specification (a drive letter followed by a
1318 //# colon) and the path specification.
1319 //# It is always true that drivespec + pathspec == p
1320 //def splitdrive(p):
1321 // """Split a pathname into drive/UNC sharepoint and relative path specifiers.
1322 // Returns a 2-tuple (drive_or_unc, path); either part may be empty.
1323 //
1324 // If you assign
1325 // result = splitdrive(p)
1326 // It is always true that:
1327 // result[0] + result[1] == p
1328 //
1329 // If the path contained a drive letter, drive_or_unc will contain everything
1330 // up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir")
1331 //
1332 // If the path contained a UNC path, the drive_or_unc will contain the host name
1333 // and share up to but not including the fourth directory separator character.
1334 // e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir")
1335 //
1336 // Paths cannot contain both a drive letter and a UNC path.
1337 //
1338 // """
1339 // if len(p) > 1:
1340 // normp = p.replace(altsep, sep)
1341 // if (normp[0:2] == sep*2) and (normp[2] != sep):
1342 // # is a UNC path:
1343 // # vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
1344 // # \\machine\mountpoint\directory\etc\...
1345 // # directory ^^^^^^^^^^^^^^^
1346 // index = normp.find(sep, 2)
1347 // if index == -1:
1348 // return '', p
1349 // index2 = normp.find(sep, index + 1)
1350 // # a UNC path can't have two slashes in a row
1351 // # (after the initial two)
1352 // if index2 == index + 1:
1353 // return '', p
1354 // if index2 == -1:
1355 // index2 = len(p)
1356 // return p[:index2], p[index2:]
1357 // if normp[1] == ':':
1358 // return p[:2], p[2:]
1359 // return '', p
1360 
1361 
1362  //On Unix, the drive is always empty.
1363  //On the Mac, the drive is always empty (don't use the volume name -- it doesn't have the same
1364  //syntactic and semantic oddities as DOS drive letters, such as there being a separate current directory per drive).
1365 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__)))
1366  return std::pair<std::string, std::string>("", pathname);
1367 #else
1368  const std::string sep = "\\";
1369  const std::string sepsep = "\\\\";
1370  const std::string altsep = "/";
1371 
1372  if(pathname.size() > 1) {
1373  std::string normPathname = pathname;
1374  std::replace(normPathname.begin(), normPathname.end(), *altsep.c_str(), *sep.c_str());
1375 
1376  if(normPathname.substr(0, 2) == sepsep && normPathname.substr(2, 1) != sep) {
1377  // is a UNC path:
1378  // vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
1379  // \\machine\mountpoint\directory\etc\...
1380  // directory ^^^^^^^^^^^^^^^
1381  size_t index = normPathname.find(sep, 2);
1382  if(index == std::string::npos) {
1383  return std::pair<std::string, std::string>("", pathname);
1384  }
1385 
1386  size_t index2 = normPathname.find(sep, index + 1);
1387  //# a UNC path can't have two slashes in a row
1388  //# (after the initial two)
1389  if(index2 == index + 1) {
1390  return std::pair<std::string, std::string>("", pathname);
1391  }
1392 
1393  if(index2 == std::string::npos) {
1394  index2 = pathname.size();
1395  }
1396 
1397  return std::pair<std::string, std::string>(pathname.substr(0, index2), pathname.substr(index2));
1398  }
1399 
1400  if(normPathname[1] == ':') {
1401  return std::pair<std::string, std::string>(pathname.substr(0, 2), pathname.substr(2));
1402  }
1403  }
1404 
1405  return std::pair<std::string, std::string>("", pathname);
1406 #endif
1407 }
#define vpDEBUG_TRACE
Definition: vpDebug.h:482
Definition of the vpMatrix class.
Definition: vpMatrix.h:98
static bool remove(const char *filename)
Definition: vpIoTools.cpp:597
void resize(const unsigned int nrows, const unsigned int ncols, const bool nullify=true)
Definition: vpMatrix.cpp:199
static bool checkDirectory(const char *dirname)
Definition: vpIoTools.cpp:315
static std::string getViSPImagesDataPath()
Definition: vpIoTools.cpp:1071
static bool isAbsolutePathname(const std::string &pathname)
Definition: vpIoTools.cpp:1291
#define vpERROR_TRACE
Definition: vpDebug.h:395
static void getVersion(const std::string &version, unsigned int &major, unsigned int &minor, unsigned int &patch)
Definition: vpIoTools.cpp:268
static std::string getFileExtension(const std::string &pathname, const bool checkFile=false)
Definition: vpIoTools.cpp:1105
Class to define colors available for display functionnalities.
Definition: vpColor.h:125
static const char separator
Definition: vpIoTools.h:184
static std::string getenv(const char *env)
Definition: vpIoTools.cpp:204
static bool rename(const char *oldfilename, const char *newfilename)
Definition: vpIoTools.cpp:655
static std::string path(const char *pathname)
Definition: vpIoTools.cpp:695
Error that can be emited by the vpIoTools class and its derivates.
Definition: vpIoException.h:72
static std::string getParent(const std::string &pathname)
Definition: vpIoTools.cpp:1220
static void createBaseNamePath(const bool &empty=false)
Definition: vpIoTools.cpp:1031
static std::string baseDir
Definition: vpIoTools.h:248
static void makeDirectory(const char *dirname)
Definition: vpIoTools.cpp:384
static bool checkFilename(const char *filename)
Definition: vpIoTools.cpp:465
static std::string createFilePath(const std::string &parent, const std::string child)
Definition: vpIoTools.cpp:1245
static bool copy(const char *src, const char *dst)
Definition: vpIoTools.cpp:531
static std::pair< std::string, std::string > splitDrive(const std::string &pathname)
Definition: vpIoTools.cpp:1315
static std::string getUserName()
Definition: vpIoTools.cpp:141
static Type minimum(const Type &a, const Type &b)
Definition: vpMath.h:148
static void saveConfigFile(const bool &actuallySave=true)
Definition: vpIoTools.cpp:1051
static std::vector< std::string > configVars
Definition: vpIoTools.h:250
static std::string getName(const std::string &pathname)
Definition: vpIoTools.cpp:1185
static std::string baseName
Definition: vpIoTools.h:247
static std::string configFile
Definition: vpIoTools.h:249
static std::string getNameWE(const std::string &pathname)
Definition: vpIoTools.cpp:1207
unsigned int getCols() const
Return the number of columns of the matrix.
Definition: vpMatrix.h:163
static vpColor getColor(const unsigned int &i)
Definition: vpColor.h:238
static bool readConfigVar(const std::string &var, float &value)
Definition: vpIoTools.cpp:791
unsigned int getRows() const
Return the number of rows of the matrix.
Definition: vpMatrix.h:161
static std::vector< std::string > configValues
Definition: vpIoTools.h:251
static bool loadConfigFile(const std::string &confFile)
Definition: vpIoTools.cpp:740
static void addNameElement(const std::string &strTrue, const bool &cond=true, const std::string &strFalse="")
Definition: vpIoTools.cpp:996