ViSP  2.8.0
vpIoTools.cpp
1 /****************************************************************************
2  *
3  * $Id: vpIoTools.cpp 4303 2013-07-04 14:14:00Z fspindle $
4  *
5  * This file is part of the ViSP software.
6  * Copyright (C) 2005 - 2013 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 #if defined UNIX
59 # include <unistd.h>
60 #elif defined WIN32
61 # include <windows.h>
62 # include <direct.h>
63 #endif
64 #ifndef WIN32
65 # include <wordexp.h>
66 #endif
67 
68 std::string vpIoTools::baseName = "";
69 std::string vpIoTools::baseDir = "";
70 std::string vpIoTools::configFile = "";
71 std::vector<std::string> vpIoTools::configVars = std::vector<std::string>();
72 std::vector<std::string> vpIoTools::configValues = std::vector<std::string>();
73 
74 
92 void
93 vpIoTools::getUserName(std::string &username)
94 {
95  // With MinGW, UNIX and WIN32 are defined
96 #if defined UNIX
97  // Get the user name.
98  char *_username = NULL;
99  _username = ::getenv("LOGNAME");
100  if (_username == NULL) {
101  vpERROR_TRACE( "Cannot get the username. Check your LOGNAME environment variable" );
103  "Cannot get the username")) ;
104  }
105  username = _username;
106 #elif defined WIN32
107  unsigned int info_buffer_size = 1024;
108  TCHAR *infoBuf = new TCHAR [info_buffer_size];
109  DWORD bufCharCount = (DWORD) info_buffer_size;
110  // Get the user name.
111  if( ! GetUserName( infoBuf, &bufCharCount ) ) {
112  delete [] infoBuf;
113  vpERROR_TRACE( "Cannot get the username" );
115  "Cannot get the username")) ;
116 
117  }
118  username = infoBuf;
119  delete [] infoBuf;
120 #endif
121 }
139 std::string
141 {
142  std::string username;
143 #if defined UNIX
144  // Get the user name.
145  char *_username = NULL;
146  _username = ::getenv("LOGNAME");
147  if (_username == NULL) {
148  vpERROR_TRACE( "Cannot get the username. Check your LOGNAME environment variable" );
150  "Cannot get the username")) ;
151  }
152  username = _username;
153 #elif defined WIN32
154  unsigned int info_buffer_size = 1024;
155  TCHAR *infoBuf = new TCHAR [info_buffer_size];
156  DWORD bufCharCount = (DWORD) info_buffer_size;
157  // Get the user name.
158  if( ! GetUserName( infoBuf, &bufCharCount ) ) {
159  delete [] infoBuf;
160  vpERROR_TRACE( "Cannot get the username" );
162  "Cannot get the username")) ;
163 
164  }
165  username = infoBuf;
166  delete [] infoBuf;
167 #endif
168  return username;
169 }
170 
207 std::string
208 vpIoTools::getenv(const char *
209 #if defined UNIX
210  env
211 #endif
212  )
213 {
214  std::string value;
215 #if defined UNIX
216  // Get the environment variable value.
217  char *_value = NULL;
218  _value = ::getenv(env);
219  if (_value == NULL) {
220  vpERROR_TRACE( "Cannot get the environment variable value" );
222  "Cannot get the environment variable value")) ;
223  }
224  value = _value;
225 
226  return value;
227 #elif defined WIN32
228 
229  vpERROR_TRACE( "Not implemented!" );
231  "Not implemented!")) ;
232 #endif
233 }
234 
272 std::string
273 vpIoTools::getenv(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 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 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 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 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 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(UNIX) && !defined(WIN32) )
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 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 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 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 #ifdef UNIX
559  sprintf(cmd, "cp -p %s %s", src, dst);
560 #elif 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 #ifdef UNIX
572  sprintf(cmd, "cp -p -r %s %s", src, dst);
573 #elif 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 #ifdef UNIX
631  sprintf(cmd, "rm -rf %s", file_or_dir);
632 #elif 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 #ifdef 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 = M_PI;
820  else if(configValues[k].compare("PI/2") == 0)
821  value = M_PI/2;
822  else if(configValues[k].compare("-PI/2") == 0)
823  value = -M_PI/2;
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, vpMatrix &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 }
#define vpDEBUG_TRACE
Definition: vpDebug.h:454
Definition of the vpMatrix class.
Definition: vpMatrix.h:96
static bool remove(const char *filename)
Definition: vpIoTools.cpp:617
void resize(const unsigned int nrows, const unsigned int ncols, const bool nullify=true)
Definition: vpMatrix.cpp:174
static bool checkDirectory(const char *dirname)
Definition: vpIoTools.cpp:335
#define vpERROR_TRACE
Definition: vpDebug.h:379
static void getVersion(const std::string &version, unsigned int &major, unsigned int &minor, unsigned int &patch)
Definition: vpIoTools.cpp:288
Class to define colors available for display functionnalities.
Definition: vpColor.h:125
static std::string getenv(const char *env)
Definition: vpIoTools.cpp:208
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:72
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 bool copy(const char *src, const char *dst)
Definition: vpIoTools.cpp:551
static std::string getUserName()
Definition: vpIoTools.cpp:140
static Type minimum(const Type &a, const Type &b)
Definition: vpMath.h:148
static void saveConfigFile(const bool &actuallySave=true)
Definition: vpIoTools.cpp:1071
static std::vector< std::string > configVars
Definition: vpIoTools.h:232
static std::string baseName
Definition: vpIoTools.h:229
static std::string configFile
Definition: vpIoTools.h:231
unsigned int getCols() const
Return the number of columns of the matrix.
Definition: vpMatrix.h:159
static vpColor getColor(const unsigned int &i)
Definition: vpColor.h:234
static bool readConfigVar(const std::string &var, float &value)
Definition: vpIoTools.cpp:811
unsigned int getRows() const
Return the number of rows of the matrix.
Definition: vpMatrix.h:157
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