Visual Servoing Platform  version 3.0.1
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
vpIoTools.cpp
1 /****************************************************************************
2  *
3  * This file is part of the ViSP software.
4  * Copyright (C) 2005 - 2017 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 #if defined(__APPLE__) && defined(__MACH__) // Apple OSX and iOS (Darwin)
66 # include <TargetConditionals.h> // To detect OSX or IOS using TARGET_OS_IOS macro
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 
78 const std::string& vpIoTools::getBuildInformation()
79 {
80  static std::string build_info =
81 #include "version_string.inc"
82  ;
83  return build_info;
84 }
85 
91 void vpIoTools::setBaseName(const std::string &s) {baseName = s;}
97 void vpIoTools::setBaseDir(const std::string &dir) {baseDir = dir + "/";}
103 std::string vpIoTools::getBaseName() {return baseName;}
109 std::string vpIoTools::getFullName() {return baseDir + baseName;}
110 
128 void
129 vpIoTools::getUserName(std::string &username)
130 {
131  // With MinGW, UNIX and _WIN32 are defined
132 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
133  // Get the user name.
134  char *_username = NULL;
135  _username = ::getenv("LOGNAME");
136  if (_username == NULL) {
137  vpERROR_TRACE( "Cannot get the username. Check your LOGNAME environment variable" );
139  "Cannot get the username")) ;
140  }
141  username = _username;
142 #elif defined(_WIN32)
143 # if ( ! defined(WINRT) )
144  unsigned int info_buffer_size = 1024;
145  TCHAR *infoBuf = new TCHAR [info_buffer_size];
146  DWORD bufCharCount = (DWORD) info_buffer_size;
147  // Get the user name.
148  if( ! GetUserName( infoBuf, &bufCharCount ) ) {
149  delete [] infoBuf;
150  throw(vpIoException(vpIoException::cantGetUserName, "Cannot get the username")) ;
151  }
152  username = infoBuf;
153  delete [] infoBuf;
154 # else
155  throw(vpIoException(vpIoException::cantGetUserName, "Cannot get the username: not implemented on Universal Windows Platform"));
156 # endif
157 #endif
158 }
176 std::string
178 {
179  std::string username;
180 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
181  // Get the user name.
182  char *_username = NULL;
183  _username = ::getenv("LOGNAME");
184  if (_username == NULL) {
185  vpERROR_TRACE( "Cannot get the username. Check your LOGNAME environment variable" );
187  "Cannot get the username")) ;
188  }
189  username = _username;
190 #elif defined(_WIN32)
191 # if ( ! defined(WINRT) )
192  unsigned int info_buffer_size = 1024;
193  TCHAR *infoBuf = new TCHAR [info_buffer_size];
194  DWORD bufCharCount = (DWORD) info_buffer_size;
195  // Get the user name.
196  if( ! GetUserName( infoBuf, &bufCharCount ) ) {
197  delete [] infoBuf;
198  vpERROR_TRACE( "Cannot get the username" );
200  "Cannot get the username")) ;
201 
202  }
203  username = infoBuf;
204  delete [] infoBuf;
205 # else
206  throw(vpIoException(vpIoException::cantGetUserName, "Cannot get the username: not implemented on Universal Windows Platform"));
207 # endif
208 #endif
209  return username;
210 }
211 
243 std::string
244 vpIoTools::getenv(const char *env)
245 {
246 #if defined(_WIN32) && defined(WINRT)
247  throw(vpIoException(vpIoException::cantGetenv, "Cannot get the environment variable value: not implemented on Universal Windows Platform"));
248 #else
249  std::string value;
250  // Get the environment variable value.
251  char *_value = NULL;
252  _value = ::getenv(env);
253  if (_value == NULL) {
255  "Cannot get the environment variable value")) ;
256  }
257  value = _value;
258 
259  return value;
260 #endif
261 }
262 
295 std::string
296 vpIoTools::getenv(const std::string &env)
297 {
298  return (vpIoTools::getenv(env.c_str()));
299 }
300 
310 void
311 vpIoTools::getVersion(const std::string &version, unsigned int &major, unsigned int &minor, unsigned int &patch)
312 {
313  if(version.size() == 0){
314  major = 0;
315  minor = 0;
316  patch = 0;
317  }
318  else{
319  size_t major_pos = version.find('.');
320  std::string major_str = version.substr(0, major_pos);
321  major = (unsigned)atoi(major_str.c_str());
322 
323  if(major_pos != std::string::npos){
324  size_t minor_pos = version.find('.', major_pos+1);
325  std::string minor_str = version.substr(major_pos+1, (minor_pos - (major_pos+1)));
326  minor = (unsigned)atoi(minor_str.c_str());
327 
328  if(minor_pos != std::string::npos){
329  std::string patch_str = version.substr(minor_pos+1);
330  patch = (unsigned)atoi(patch_str.c_str());
331  }
332  else{
333  patch = 0;
334  }
335  }
336  else{
337  minor = 0;
338  patch = 0;
339  }
340  }
341 }
342 
357 bool
358 vpIoTools::checkDirectory(const char *dirname )
359 {
360 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
361  struct stat stbuf;
362 #elif defined(_WIN32)
363  struct _stat stbuf;
364 #endif
365 
366  if ( dirname == NULL || dirname[0] == '\0' ) {
367  return false;
368  }
369 
370  std::string _dirname = path(dirname);
371 
372 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
373  if ( stat( _dirname.c_str(), &stbuf ) != 0 )
374 #elif defined(_WIN32)
375  if ( _stat( _dirname.c_str(), &stbuf ) != 0 )
376 #endif
377  {
378  return false;
379  }
380  if ( (stbuf.st_mode & S_IFDIR) == 0 ) {
381  return false;
382  }
383 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
384  if ( (stbuf.st_mode & S_IWUSR) == 0 )
385 #elif defined(_WIN32)
386  if ( (stbuf.st_mode & S_IWRITE) == 0 )
387 #endif
388  {
389  return false;
390  }
391  return true;
392 }
393 
407 bool
408 vpIoTools::checkDirectory(const std::string &dirname )
409 {
410  return vpIoTools::checkDirectory(dirname.c_str());
411 }
426 void
427 vpIoTools::makeDirectory(const char *dirname )
428 {
429 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
430  struct stat stbuf;
431 #elif defined(_WIN32)
432  struct _stat stbuf;
433 #endif
434 
435  if ( dirname == NULL || dirname[0] == '\0' ) {
436  vpERROR_TRACE( "invalid directory name\n");
438  "invalid directory name")) ;
439  }
440 
441  std::string _dirname = path(dirname);
442 
443 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
444  if ( stat( _dirname.c_str(), &stbuf ) != 0 )
445 #elif defined(_WIN32)
446  if ( _stat( _dirname.c_str(), &stbuf ) != 0 )
447 #endif
448  {
449 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__)))
450  if ( mkdir( _dirname.c_str(), (mode_t)0755 ) != 0 )
451 #elif defined(_WIN32)
452  if ( _mkdir( _dirname.c_str()) != 0 )
453 #endif
454  {
455  vpERROR_TRACE("unable to create directory '%s'\n", dirname );
457  "unable to create directory")) ;
458  }
459  vpDEBUG_TRACE(2,"has created directory '%s'\n", dirname );
460  }
461 
462  if ( checkDirectory( dirname ) == false) {
463  vpERROR_TRACE("unable to create directory '%s'\n", dirname );
465  "unable to create directory")) ;
466  }
467 }
468 
481 void
482 vpIoTools::makeDirectory(const std::string &dirname )
483 {
484  try {
485  vpIoTools::makeDirectory(dirname.c_str());
486  }
487  catch (...) {
488  vpERROR_TRACE("unable to create directory '%s'\n",dirname.c_str());
490  "unable to create directory")) ;
491  }
492 }
493 
507 bool
508 vpIoTools::checkFilename(const char *filename)
509 {
510 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
511  struct stat stbuf;
512 #elif defined(_WIN32)
513  struct _stat stbuf;
514 #endif
515 
516  if ( filename == NULL || filename[0] == '\0' ) {
517  return false;
518  }
519 
520  std::string _filename = path(filename);
521 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
522  if ( stat( _filename.c_str(), &stbuf ) != 0 )
523 #elif defined(_WIN32)
524  if ( _stat( _filename.c_str(), &stbuf ) != 0 )
525 #endif
526  {
527  return false;
528  }
529  if ( (stbuf.st_mode & S_IFREG) == 0 ) {
530  return false;
531  }
532 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
533  if ( (stbuf.st_mode & S_IRUSR) == 0 )
534 #elif defined(_WIN32)
535  if ( (stbuf.st_mode & S_IREAD) == 0 )
536 #endif
537  {
538  return false;
539  }
540  return true;
541 }
542 
555 bool
556 vpIoTools::checkFilename(const std::string &filename)
557 {
558  return vpIoTools::checkFilename(filename.c_str());
559 }
560 
573 bool
574 vpIoTools::copy(const char *src, const char *dst)
575 {
576  // Check if we have to consider a file or a directory
577  if ( vpIoTools::checkFilename(src) ) {
578  //std::cout << "copy file: " << src << " in " << dst << std::endl;
579 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
580  char cmd[FILENAME_MAX];
581  int ret;
582  sprintf(cmd, "cp -p %s %s", src, dst);
583  ret = system(cmd);
584  if (ret) {}; // to avoid a warning
585  //std::cout << cmd << " return value: " << ret << std::endl;
586  return true;
587 #elif defined(_WIN32)
588 # if ( ! defined(WINRT) )
589  char cmd[FILENAME_MAX];
590  int ret;
591  std::string src_ = vpIoTools::path(src);
592  std::string dst_ = vpIoTools::path(dst);
593  sprintf(cmd, "copy %s %s", src_.c_str(), dst_.c_str());
594  ret = system(cmd);
595  if (ret) {}; // to avoid a warning
596  //std::cout << cmd << " return value: " << ret << std::endl;
597  return true;
598 # else
599  throw(vpIoException(vpException::fatalError, "Cannot copy %s in %s: not implemented on Universal Windows Platform", src, dst));
600 # endif
601 #endif
602  }
603  else if ( vpIoTools::checkDirectory(src) ) {
604  //std::cout << "copy directory: " << src << " in " << dst << std::endl;
605 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
606  char cmd[FILENAME_MAX];
607  int ret;
608  sprintf(cmd, "cp -p -r %s %s", src, dst);
609  ret = system(cmd);
610  if (ret) {}; // to avoid a warning
611  //std::cout << cmd << " return value: " << ret << std::endl;
612  return true;
613 #elif defined(_WIN32)
614 # if ( ! defined(WINRT) )
615  char cmd[FILENAME_MAX];
616  int ret;
617  std::string src_ = vpIoTools::path(src);
618  std::string dst_ = vpIoTools::path(dst);
619  sprintf(cmd, "copy %s %s", src_.c_str(), dst_.c_str());
620  ret = system(cmd);
621  if (ret) {}; // to avoid a warning
622  //std::cout << cmd << " return value: " << ret << std::endl;
623  return true;
624 # else
625  throw(vpIoException(vpException::fatalError, "Cannot copy %s in %s: not implemented on Universal Windows Platform", src, dst));
626 # endif
627 #endif
628  }
629  else {
630  std::cout << "Cannot copy: " << src << " in " << dst << std::endl;
631  return false;
632  }
633 }
646 bool
647 vpIoTools::copy(const std::string &src, const std::string &dst)
648 {
649  return vpIoTools::copy(src.c_str(), dst.c_str());
650 }
651 
662 bool
663 vpIoTools::remove(const char *file_or_dir)
664 {
665  // Check if we have to consider a file or a directory
666  if ( vpIoTools::checkFilename(file_or_dir) ) {
667  //std::cout << "remove file: " << file_or_dir << std::endl;
668  if (::remove(file_or_dir) != 0)
669  return false;
670  else
671  return true;
672  }
673  else if ( vpIoTools::checkDirectory(file_or_dir) ) {
674  //std::cout << "remove directory: " << file_or_dir << std::endl;
675 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
676  char cmd[FILENAME_MAX];
677  sprintf(cmd, "rm -rf %s", file_or_dir);
678  int ret = system(cmd);
679  if (ret) {}; // to avoid a warning
680  //std::cout << cmd << " return value: " << ret << std::endl;
681  return true;
682 #elif defined(_WIN32)
683 # if ( ! defined(WINRT) )
684  char cmd[FILENAME_MAX];
685  std::string file_or_dir_ = vpIoTools::path(file_or_dir);
686  sprintf(cmd, "rmdir /S /Q %s", file_or_dir_.c_str());
687  int ret = system(cmd);
688  if (ret) {}; // to avoid a warning
689  //std::cout << cmd << " return value: " << ret << std::endl;
690  return true;
691 # else
692  throw(vpIoException(vpException::fatalError, "Cannot remove %s: not implemented on Universal Windows Platform", file_or_dir));
693 # endif
694 #endif
695  }
696  else {
697  std::cout << "Cannot remove: " << file_or_dir << std::endl;
698  return false;
699  }
700 }
712 bool
713 vpIoTools::remove(const std::string &file_or_dir)
714 {
715  return vpIoTools::remove(file_or_dir.c_str());
716 }
717 
729 bool
730 vpIoTools::rename(const char *oldfilename, const char *newfilename)
731 {
732  if (::rename(oldfilename, newfilename) != 0)
733  return false;
734  else
735  return true;
736 }
737 
749 bool
750 vpIoTools::rename(const std::string &oldfilename, const std::string &newfilename)
751 {
752  return vpIoTools::rename(oldfilename.c_str(), newfilename.c_str());
753 }
754 
755 
756 
769 std::string
770 vpIoTools::path(const char *pathname)
771 {
772  std::string path(pathname);
773 
774 #if defined(_WIN32)
775  for(unsigned int i=0 ; i<path.length() ; i++)
776  if( path[i] == '/') path[i] = '\\';
777 #elif defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))
778  for(unsigned int i=0 ; i<path.length() ; i++)
779  if( path[i] == '\\') path[i] = '/';
780 # if TARGET_OS_IOS == 0 // The following code is not working on iOS since wordexp() is not available
781  wordexp_t exp_result;
782 
783  wordexp(path.c_str(), &exp_result, 0);
784  path = "";
785  //If path contains whitespace, wordexp_t will try to expand each word separated by whitespaces
786  //This is why we need to concatenate the results
787  for(size_t i = 0; i < exp_result.we_wordc; i++) {
788  path += exp_result.we_wordv[i];
789  if(i < exp_result.we_wordc-1) {
790  path += " ";
791  }
792  }
793  wordfree(&exp_result);
794 # endif
795 #endif
796 
797  return path;
798 }
799 
812 std::string
813 vpIoTools::path(const std::string &pathname)
814 {
815  return path(pathname.c_str());
816 }
817 
818 
826 bool vpIoTools::loadConfigFile(const std::string &confFile)
827 {
828  configFile = path(confFile);
829  configVars.clear();configValues.clear();
830  std::ifstream confContent(configFile.c_str(), std::ios::in);
831 
832  if(confContent.is_open())
833  {
834  std::string line,var,val;
835  long unsigned int k;
836  int c;
837  std::string stop[3] = {" ", "\t", "#"};
838  while(std::getline(confContent, line))
839  {
840  if((line.compare(0,1,"#") != 0) && (line.size() > 2))
841  {
842  try
843  {
844  // name of the variable
845  k = (unsigned long)line.find(" ");
846  var = line.substr(0,k);
847  // look for the end of the actual value
848  c = 200;
849  for(unsigned i=0;i<3;++i)
850  c = vpMath::minimum(c,(int)line.find(stop[i],k+1));
851  if(c==-1)
852  c = (int)line.size();
853  long unsigned int c_ = (long unsigned int) c;
854  val = line.substr(k+1,c_-k-1);
855  configVars.push_back(var);
856  configValues.push_back(val);
857  }
858  catch(...){}
859  }
860  }
861  confContent.close();
862  }
863  else {
864  return false;
865  }
866  return true;
867 }
868 
877 bool vpIoTools::readConfigVar(const std::string &var, float &value)
878 {
879  bool found = false;
880  for(unsigned int k=0;k<configVars.size() && found==false;++k)
881  {
882  if(configVars[k] == var)
883  {
884  if(configValues[k].compare("PI") == 0)
885  value = (float) M_PI;
886  else if(configValues[k].compare("PI/2") == 0)
887  value = (float) (M_PI/2.0);
888  else if(configValues[k].compare("-PI/2") == 0)
889  value = (float) (-M_PI/2.0);
890  else
891  value = (float) atof(configValues[k].c_str());
892  found = true;
893  }
894  }
895  if(found == false)
896  std::cout << var << " not found in config file" << std::endl;
897  return found;
898 }
907 bool vpIoTools::readConfigVar(const std::string &var, double &value)
908 {
909  bool found = false;
910  for(unsigned int k=0;k<configVars.size() && found==false;++k)
911  {
912  if(configVars[k] == var)
913  {
914  if(configValues[k].compare("PI") == 0)
915  value = M_PI;
916  else if(configValues[k].compare("PI/2") == 0)
917  value = M_PI/2;
918  else if(configValues[k].compare("-PI/2") == 0)
919  value = -M_PI/2;
920  else
921  value = atof(configValues[k].c_str());
922  found = true;
923  }
924  }
925  if(found == false)
926  std::cout << var << " not found in config file" << std::endl;
927  return found;
928 }
929 
938 bool vpIoTools::readConfigVar(const std::string &var, int &value)
939 {
940  bool found = false;
941  for(unsigned int k=0;k<configVars.size() && found==false;++k)
942  {
943  if(configVars[k] == var)
944  {
945  value = atoi(configValues[k].c_str());
946  found = true;
947  }
948  }
949  if(found == false)
950  std::cout << var << " not found in config file" << std::endl;
951  return found;
952 }
953 
962 bool vpIoTools::readConfigVar(const std::string &var, unsigned int &value)
963 {
964  int v = 0;
965  bool found = readConfigVar(var,v);
966  value = (unsigned int) v;
967  return found;
968 }
969 
978 bool vpIoTools::readConfigVar(const std::string &var, bool &value)
979 {
980  int v = 0;
981  bool found = readConfigVar(var,v);
982  value = (v!=0);
983  return found;
984 }
985 
994 bool vpIoTools::readConfigVar(const std::string &var, vpColor &value)
995 {
996  unsigned int v = 0;
997  bool found = readConfigVar(var,v);
998  value = vpColor::getColor(v);
999  return found;
1000 }
1001 
1010 bool vpIoTools::readConfigVar(const std::string &var, std::string &value)
1011 {
1012  bool found = false;
1013  for(unsigned int k=0;k<configVars.size() && found==false;++k)
1014  {
1015  if(configVars[k] == var)
1016  {
1017  value = configValues[k];
1018  found = true;
1019  }
1020  }
1021  if(found == false)
1022  std::cout << var << " not found in config file" << std::endl;
1023  return found;
1024 }
1025 
1038 bool vpIoTools::readConfigVar(const std::string &var, vpArray2D<double> &value, const unsigned int &nCols, const unsigned int &nRows)
1039 {
1040  bool found = false;
1041  std::string nb;
1042  for(unsigned int k=0;k<configVars.size() && found==false;++k)
1043  {
1044  if(configVars[k] == var)
1045  {
1046  found = true;
1047  // resize or not
1048  if(nCols != 0 && nRows != 0)
1049  value.resize(nRows, nCols);
1050  size_t ind=0,ind2;
1051  for(unsigned int i=0;i<value.getRows();++i)
1052  for(unsigned int j=0;j<value.getCols();++j)
1053  {
1054  ind2 = configValues[k].find(",",ind);
1055  nb = configValues[k].substr(ind,ind2-ind);
1056  if(nb.compare("PI") == 0)
1057  value[i][j] = M_PI;
1058  else if(nb.compare("PI/2") == 0)
1059  value[i][j] = M_PI/2;
1060  else if(nb.compare("-PI/2") == 0)
1061  value[i][j] = -M_PI/2;
1062  else
1063  value[i][j] = atof(nb.c_str());
1064  ind = ind2+1;
1065  }
1066  }
1067  }
1068  if(found == false)
1069  std::cout << var << " not found in config file" << std::endl;
1070  return found;
1071 }
1072 
1073 // construct experiment filename & path
1074 
1082 void vpIoTools::addNameElement(const std::string &strTrue, const bool &cond, const std::string &strFalse)
1083 {
1084  if(cond)
1085  baseName += "_" + strTrue;
1086  else if(strFalse != "")
1087  baseName += "_" + strFalse;
1088 }
1089 
1097 void vpIoTools::addNameElement(const std::string &strTrue, const double &val)
1098 {
1099  //if(val != 0.)
1100  if(std::fabs(val) < std::numeric_limits<double>::epsilon())
1101  {
1102  char valC[256];
1103  sprintf(valC, "%.3f", val);
1104  std::string valS(valC);
1105  baseName += "_" + strTrue + valS;
1106  }
1107 }
1108 
1117 void vpIoTools::createBaseNamePath(const bool &empty)
1118 {
1119  if(vpIoTools::checkDirectory(baseDir + baseName) == false) {
1121  std::cout << "creating directory " + baseDir + baseName << std::endl;
1122  }
1123  else {
1124  if(empty) {
1125  std::cout << "emptying directory " + baseDir + baseName << std::endl;
1127  }
1128  }
1129 }
1130 
1137 void vpIoTools::saveConfigFile(const bool &actuallySave)
1138 {
1139  if(actuallySave) {
1140  std::string dest = baseDir + "/" + baseName + "_config.txt";
1141  // file copy
1142  vpIoTools::copy(configFile, dest);
1143  }
1144 }
1145 
1158 {
1159  std::string data_path;
1160  std::string file_to_test("ViSP-images/mbt/cube.cao");
1161  std::string filename;
1162 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
1163  // Test if visp-images-data package is u-installed (Ubuntu and Debian)
1164  data_path = "/usr/share/visp-images-data";
1165  filename = data_path + "/" + file_to_test;
1166  if (vpIoTools::checkFilename(filename))
1167  return data_path;
1168 #endif
1169  // Test if VISP_INPUT_IMAGE_PATH env var is set
1170  try {
1171  data_path = vpIoTools::getenv("VISP_INPUT_IMAGE_PATH");
1172  filename = data_path + "/" + file_to_test;
1173  if (vpIoTools::checkFilename(filename))
1174  return data_path;
1175  }
1176  catch(...) {
1177  }
1178  data_path = "";
1179  return data_path;
1180 }
1181 
1191 std::string vpIoTools::getFileExtension(const std::string& pathname, const bool checkFile)
1192 {
1193  if(checkFile && (vpIoTools::checkDirectory(pathname) || !vpIoTools::checkFilename(pathname))) {
1194  return "";
1195  }
1196 
1197 #if defined(_WIN32)
1198  std::string sep = "\\";
1199  std::string altsep = "/";
1200  std::string extsep = ".";
1201 #else
1202  //On Unix, or on the Mac
1203  std::string sep = "/";
1204  std::string altsep = "";
1205  std::string extsep = ".";
1206 #endif
1207 
1208  //Python 2.7.8 module.
1209 //# Split a path in root and extension.
1210 //# The extension is everything starting at the last dot in the last
1211 //# pathname component; the root is everything before that.
1212 //# It is always true that root + ext == p.
1213 //
1214 //# Generic implementation of splitext, to be parametrized with
1215 //# the separators
1216 //def _splitext(p, sep, altsep, extsep):
1217 // """Split the extension from a pathname.
1218 //
1219 // Extension is everything from the last dot to the end, ignoring
1220 // leading dots. Returns "(root, ext)"; ext may be empty."""
1221 //
1222 // sepIndex = p.rfind(sep)
1223 // if altsep:
1224 // altsepIndex = p.rfind(altsep)
1225 // sepIndex = max(sepIndex, altsepIndex)
1226 //
1227 // dotIndex = p.rfind(extsep)
1228 // if dotIndex > sepIndex:
1229 // # skip all leading dots
1230 // filenameIndex = sepIndex + 1
1231 // while filenameIndex < dotIndex:
1232 // if p[filenameIndex] != extsep:
1233 // return p[:dotIndex], p[dotIndex:]
1234 // filenameIndex += 1
1235 //
1236 // return p, ''
1237 
1238  int sepIndex = (int)pathname.rfind(sep);
1239  if(!altsep.empty()) {
1240  int altsepIndex = (int)pathname.rfind(altsep);
1241  sepIndex = (std::max)(sepIndex, altsepIndex);
1242  }
1243 
1244  size_t dotIndex = pathname.rfind(extsep);
1245  if(dotIndex != std::string::npos) {
1246  //The extsep character exists
1247  if((sepIndex != (int)std::string::npos && (int)dotIndex > sepIndex) || sepIndex == (int)std::string::npos) {
1248  if(sepIndex == (int)std::string::npos) {
1249  sepIndex = -1;
1250  }
1251  size_t filenameIndex = (size_t)(sepIndex + 1);
1252 
1253  while(filenameIndex < dotIndex) {
1254  if(pathname.compare(filenameIndex, 1, extsep) != 0) {
1255  return pathname.substr(dotIndex);
1256  }
1257  filenameIndex++;
1258  }
1259  }
1260  }
1261 
1262 
1263  return "";
1264 }
1265 
1271 std::string vpIoTools::getName(const std::string& pathname)
1272 {
1273  if(pathname.size() > 0)
1274  {
1275  std::string convertedPathname = vpIoTools::path(pathname);
1276 
1277  size_t index = convertedPathname.find_last_of(vpIoTools::separator);
1278  if(index != std::string::npos) {
1279  return convertedPathname.substr(index + 1);
1280  }
1281 
1282  return convertedPathname;
1283  }
1284 
1285  return "";
1286 }
1287 
1293 std::string vpIoTools::getNameWE(const std::string& pathname)
1294 {
1295  std::string name = vpIoTools::getName(pathname);
1296  size_t found = name.find_last_of(".");
1297  std::string name_we = name.substr(0, found);
1298  return name_we;
1299 }
1300 
1306 std::string vpIoTools::getParent(const std::string& pathname)
1307 {
1308  if(pathname.size() > 0)
1309  {
1310  std::string convertedPathname = vpIoTools::path(pathname);
1311 
1312  size_t index = convertedPathname.find_last_of(vpIoTools::separator);
1313  if(index != std::string::npos) {
1314  return convertedPathname.substr(0, index);
1315  }
1316  }
1317 
1318  return "";
1319 }
1320 
1328 std::string vpIoTools::getAbsolutePathname(const std::string &pathname) {
1329 
1330 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX
1331  std::string real_path_str = pathname;
1332  char *real_path = realpath(pathname.c_str(), NULL);
1333 
1334  if (real_path != NULL) {
1335  real_path_str = real_path;
1336  free(real_path);
1337  }
1338  return real_path_str;
1339 #elif defined(_WIN32)
1340 # if ( ! defined(WINRT) )
1341  std::string real_path_str = pathname;
1342  DWORD retval = 0;
1343  TCHAR buffer[4096] = TEXT("");
1344 
1345  retval = GetFullPathName(pathname.c_str(), 4096, buffer, 0);
1346  if (retval != 0) {
1347  real_path_str = buffer;
1348  }
1349  return real_path_str;
1350 # else
1351  throw(vpIoException(vpException::fatalError, "Cannot get absolute path of %s: not implemented on Universal Windows Platform", pathname.c_str()));
1352 # endif
1353 #endif
1354 }
1355 
1366 std::string vpIoTools::createFilePath(const std::string& parent, const std::string child)
1367 {
1368  if(child.size() == 0 && parent.size() == 0)
1369  {
1370  return "";
1371  }
1372 
1373  if(child.size() == 0)
1374  {
1375  return vpIoTools::path(parent);
1376  }
1377 
1378  if(parent.size() == 0)
1379  {
1380  return vpIoTools::path(child);
1381  }
1382 
1383  std::string convertedParent = vpIoTools::path(parent);
1384  std::string convertedChild = vpIoTools::path(child);
1385 
1386  std::stringstream ss;
1387  ss << vpIoTools::separator;
1388  std::string stringSeparator;
1389  ss >> stringSeparator;
1390 
1391  std::string lastConvertedParentChar = convertedParent.substr(convertedParent.size() - 1);
1392  std::string firstConvertedChildChar = convertedChild.substr(0, 1);
1393 
1394  if(lastConvertedParentChar == stringSeparator)
1395  {
1396  convertedParent = convertedParent.substr(0, convertedParent.size() - 1);
1397  }
1398 
1399  if(firstConvertedChildChar == stringSeparator)
1400  {
1401  convertedChild = convertedChild.substr(1);
1402  }
1403 
1404  return std::string(convertedParent + vpIoTools::separator + convertedChild);
1405 }
1406 
1412 bool vpIoTools::isAbsolutePathname(const std::string& pathname)
1413 {
1414  //# Inspired by the Python 2.7.8 module.
1415  //# Return whether a path is absolute.
1416  //# Trivial in Posix, harder on the Mac or MS-DOS.
1417  //# For DOS it is absolute if it starts with a slash or backslash (current
1418  //# volume), or if a pathname after the volume letter and colon / UNC resource
1419  //# starts with a slash or backslash.
1420  //
1421  //def isabs(s):
1422  // """Test whether a path is absolute"""
1423  // s = splitdrive(s)[1]
1424  // return s != '' and s[:1] in '/\\'
1425  std::string path = splitDrive(pathname).second;
1426  return path.size() > 0 && (path.substr(0, 1) == "/" || path.substr(0, 1) == "\\");
1427 }
1428 
1435 bool vpIoTools::isSamePathname(const std::string& pathname1, const std::string& pathname2) {
1436  //Normalize path
1437  std::string path1_normalize = vpIoTools::path(pathname1);
1438  std::string path2_normalize = vpIoTools::path(pathname2);
1439 
1440  //Get absolute path
1441  path1_normalize = vpIoTools::getAbsolutePathname(path1_normalize);
1442  path2_normalize = vpIoTools::getAbsolutePathname(path2_normalize);
1443 
1444  return (path1_normalize == path2_normalize);
1445 }
1446 
1454 std::pair<std::string, std::string> vpIoTools::splitDrive(const std::string& pathname)
1455 {
1456 //# Split a path in a drive specification (a drive letter followed by a
1457 //# colon) and the path specification.
1458 //# It is always true that drivespec + pathspec == p
1459 //def splitdrive(p):
1460 // """Split a pathname into drive/UNC sharepoint and relative path specifiers.
1461 // Returns a 2-tuple (drive_or_unc, path); either part may be empty.
1462 //
1463 // If you assign
1464 // result = splitdrive(p)
1465 // It is always true that:
1466 // result[0] + result[1] == p
1467 //
1468 // If the path contained a drive letter, drive_or_unc will contain everything
1469 // up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir")
1470 //
1471 // If the path contained a UNC path, the drive_or_unc will contain the host name
1472 // and share up to but not including the fourth directory separator character.
1473 // e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir")
1474 //
1475 // Paths cannot contain both a drive letter and a UNC path.
1476 //
1477 // """
1478 // if len(p) > 1:
1479 // normp = p.replace(altsep, sep)
1480 // if (normp[0:2] == sep*2) and (normp[2] != sep):
1481 // # is a UNC path:
1482 // # vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
1483 // # \\machine\mountpoint\directory\etc\...
1484 // # directory ^^^^^^^^^^^^^^^
1485 // index = normp.find(sep, 2)
1486 // if index == -1:
1487 // return '', p
1488 // index2 = normp.find(sep, index + 1)
1489 // # a UNC path can't have two slashes in a row
1490 // # (after the initial two)
1491 // if index2 == index + 1:
1492 // return '', p
1493 // if index2 == -1:
1494 // index2 = len(p)
1495 // return p[:index2], p[index2:]
1496 // if normp[1] == ':':
1497 // return p[:2], p[2:]
1498 // return '', p
1499 
1500 
1501  //On Unix, the drive is always empty.
1502  //On the Mac, the drive is always empty (don't use the volume name -- it doesn't have the same
1503  //syntactic and semantic oddities as DOS drive letters, such as there being a separate current directory per drive).
1504 #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__)))
1505  return std::pair<std::string, std::string>("", pathname);
1506 #else
1507  const std::string sep = "\\";
1508  const std::string sepsep = "\\\\";
1509  const std::string altsep = "/";
1510 
1511  if(pathname.size() > 1) {
1512  std::string normPathname = pathname;
1513  std::replace(normPathname.begin(), normPathname.end(), *altsep.c_str(), *sep.c_str());
1514 
1515  if(normPathname.substr(0, 2) == sepsep && normPathname.substr(2, 1) != sep) {
1516  // is a UNC path:
1517  // vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
1518  // \\machine\mountpoint\directory\etc\...
1519  // directory ^^^^^^^^^^^^^^^
1520  size_t index = normPathname.find(sep, 2);
1521  if(index == std::string::npos) {
1522  return std::pair<std::string, std::string>("", pathname);
1523  }
1524 
1525  size_t index2 = normPathname.find(sep, index + 1);
1526  //# a UNC path can't have two slashes in a row
1527  //# (after the initial two)
1528  if(index2 == index + 1) {
1529  return std::pair<std::string, std::string>("", pathname);
1530  }
1531 
1532  if(index2 == std::string::npos) {
1533  index2 = pathname.size();
1534  }
1535 
1536  return std::pair<std::string, std::string>(pathname.substr(0, index2), pathname.substr(index2));
1537  }
1538 
1539  if(normPathname[1] == ':') {
1540  return std::pair<std::string, std::string>(pathname.substr(0, 2), pathname.substr(2));
1541  }
1542  }
1543 
1544  return std::pair<std::string, std::string>("", pathname);
1545 #endif
1546 }
1547 
1596 std::vector<std::string> vpIoTools::splitChain(const std::string & chain, const std::string & sep)
1597 {
1598  size_t startIndex = 0;
1599 
1600  std::string chainToSplit = chain;
1601  std::vector<std::string> subChain;
1602  size_t sepIndex = chainToSplit.find(sep);
1603 
1604  while(sepIndex != std::string::npos) {
1605  std::string sub = chainToSplit.substr(startIndex, sepIndex);
1606  if (! sub.empty())
1607  subChain.push_back( sub );
1608  chainToSplit = chainToSplit.substr(sepIndex+1, chain.size()-1);
1609 
1610  sepIndex = chainToSplit.find(sep);
1611  }
1612  if (!chainToSplit.empty())
1613  subChain.push_back(chainToSplit);
1614 
1615  return subChain;
1616 }
static bool remove(const char *filename)
Definition: vpIoTools.cpp:663
static bool checkDirectory(const char *dirname)
Definition: vpIoTools.cpp:358
static std::string getViSPImagesDataPath()
Definition: vpIoTools.cpp:1157
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:1412
static void getVersion(const std::string &version, unsigned int &major, unsigned int &minor, unsigned int &patch)
Definition: vpIoTools.cpp:311
static std::string getFileExtension(const std::string &pathname, const bool checkFile=false)
Definition: vpIoTools.cpp:1191
#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:181
static std::string getenv(const char *env)
Definition: vpIoTools.cpp:244
static bool rename(const char *oldfilename, const char *newfilename)
Definition: vpIoTools.cpp:730
static std::string path(const char *pathname)
Definition: vpIoTools.cpp:770
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:1306
static void createBaseNamePath(const bool &empty=false)
Definition: vpIoTools.cpp:1117
static const std::string & getBuildInformation()
Definition: vpIoTools.cpp:78
static std::string baseDir
Definition: vpIoTools.h:233
static void makeDirectory(const char *dirname)
Definition: vpIoTools.cpp:427
static bool checkFilename(const char *filename)
Definition: vpIoTools.cpp:508
static void setBaseName(const std::string &s)
Definition: vpIoTools.cpp:91
static std::string createFilePath(const std::string &parent, const std::string child)
Definition: vpIoTools.cpp:1366
static bool copy(const char *src, const char *dst)
Definition: vpIoTools.cpp:574
static std::pair< std::string, std::string > splitDrive(const std::string &pathname)
Definition: vpIoTools.cpp:1454
static bool isSamePathname(const std::string &pathname1, const std::string &pathname2)
Definition: vpIoTools.cpp:1435
static std::string getUserName()
Definition: vpIoTools.cpp:177
static std::vector< std::string > splitChain(const std::string &chain, const std::string &sep)
Definition: vpIoTools.cpp:1596
static Type minimum(const Type &a, const Type &b)
Definition: vpMath.h:151
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:1137
static std::vector< std::string > configVars
Definition: vpIoTools.h:235
static std::string getName(const std::string &pathname)
Definition: vpIoTools.cpp:1271
static std::string baseName
Definition: vpIoTools.h:232
static std::string getFullName()
Definition: vpIoTools.cpp:109
static std::string configFile
Definition: vpIoTools.h:234
static void setBaseDir(const std::string &dir)
Definition: vpIoTools.cpp:97
static std::string getNameWE(const std::string &pathname)
Definition: vpIoTools.cpp:1293
static std::string getBaseName()
Definition: vpIoTools.cpp:103
#define vpDEBUG_TRACE
Definition: vpDebug.h:478
static std::string getAbsolutePathname(const std::string &pathname)
Definition: vpIoTools.cpp:1328
static vpColor getColor(const unsigned int &i)
Definition: vpColor.h:234
static bool readConfigVar(const std::string &var, float &value)
Definition: vpIoTools.cpp:877
static std::vector< std::string > configValues
Definition: vpIoTools.h:236
static bool loadConfigFile(const std::string &confFile)
Definition: vpIoTools.cpp:826
static void addNameElement(const std::string &strTrue, const bool &cond=true, const std::string &strFalse="")
Definition: vpIoTools.cpp:1082