ViSP  2.7.0
vpIoTools.cpp
1 /****************************************************************************
2  *
3  * $Id: vpIoTools.cpp 4056 2013-01-05 13:04:42Z 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 
758 void vpIoTools::loadConfigFile(const std::string &confFile)
759 {
760  configFile = path(confFile);
761  configVars.clear();configValues.clear();
762  std::ifstream confContent(configFile.c_str(), std::ios::in);
763 
764  if(confContent)
765  {
766  std::string line,var,val;
767  long unsigned int k;
768  int c;
769  std::string stop[3] = {" ", "\t", "#"};
770  while(std::getline(confContent, line))
771  {
772  if((line.find("#",0,1) != 0) && (line.size() > 2))
773  {
774  try
775  {
776  // name of the variable
777  k = line.find(" ");
778  var = line.substr(0,k);
779  // look for the end of the actual value
780  c = 200;
781  for(unsigned i=0;i<3;++i)
782  c = vpMath::minimum(c,(int)line.find(stop[i],k+1));
783  if(c==-1)
784  c = (int)line.size();
785  long unsigned int c_ = (long unsigned int) c;
786  val = line.substr(k+1,c_-k-1);
787  configVars.push_back(var);
788  configValues.push_back(val);
789  }
790  catch(...){}
791  }
792  }
793  confContent.close();
794  }
795 }
796 
805 bool vpIoTools::readConfigVar(const std::string &var, double &value)
806 {
807  bool found = false;
808  for(unsigned int k=0;k<configVars.size() && found==false;++k)
809  {
810  if(configVars[k] == var)
811  {
812  if(configValues[k].compare("PI") == 0)
813  value = M_PI;
814  else if(configValues[k].compare("PI/2") == 0)
815  value = M_PI/2;
816  else if(configValues[k].compare("-PI/2") == 0)
817  value = -M_PI/2;
818  else
819  value = atof(configValues[k].c_str());
820  found = true;
821  }
822  }
823  if(found == false)
824  std::cout << var << " not found in config file" << std::endl;
825  return found;
826 }
827 
836 bool vpIoTools::readConfigVar(const std::string &var, int &value)
837 {
838  bool found = false;
839  for(unsigned int k=0;k<configVars.size() && found==false;++k)
840  {
841  if(configVars[k] == var)
842  {
843  value = atoi(configValues[k].c_str());
844  found = true;
845  }
846  }
847  if(found == false)
848  std::cout << var << " not found in config file" << std::endl;
849  return found;
850 }
851 
860 bool vpIoTools::readConfigVar(const std::string &var, unsigned int &value)
861 {
862  int v = 0;
863  bool found = readConfigVar(var,v);
864  value = (unsigned int) v;
865  return found;
866 }
867 
876 bool vpIoTools::readConfigVar(const std::string &var, bool &value)
877 {
878  int v = 0;
879  bool found = readConfigVar(var,v);
880  value = (v!=0);
881  return found;
882 }
883 
892 bool vpIoTools::readConfigVar(const std::string &var, vpColor &value)
893 {
894  unsigned int v = 0;
895  bool found = readConfigVar(var,v);
896  value = vpColor::getColor(v);
897  return found;
898 }
899 
908 bool vpIoTools::readConfigVar(const std::string &var, std::string &value)
909 {
910  bool found = false;
911  for(unsigned int k=0;k<configVars.size() && found==false;++k)
912  {
913  if(configVars[k] == var)
914  {
915  value = configValues[k];
916  found = true;
917  }
918  }
919  if(found == false)
920  std::cout << var << " not found in config file" << std::endl;
921  return found;
922 }
923 
936 bool vpIoTools::readConfigVar(const std::string &var, vpMatrix &value, const unsigned int &nCols, const unsigned int &nRows)
937 {
938  bool found = false;
939  std::string nb;
940  for(unsigned int k=0;k<configVars.size() && found==false;++k)
941  {
942  if(configVars[k] == var)
943  {
944  found = true;
945  // resize or not
946  if(nCols != 0 && nRows != 0)
947  value.resize(nRows, nCols);
948  long unsigned int ind=0,ind2;
949  for(unsigned int i=0;i<value.getRows();++i)
950  for(unsigned int j=0;j<value.getCols();++j)
951  {
952  ind2 = configValues[k].find(",",ind);
953  nb = configValues[k].substr(ind,ind2-ind);
954  if(nb.compare("PI") == 0)
955  value[i][j] = M_PI;
956  else if(nb.compare("PI/2") == 0)
957  value[i][j] = M_PI/2;
958  else if(nb.compare("-PI/2") == 0)
959  value[i][j] = -M_PI/2;
960  else
961  value[i][j] = atof(nb.c_str());
962  ind = ind2+1;
963  }
964  }
965  }
966  if(found == false)
967  std::cout << var << " not found in config file" << std::endl;
968  return found;
969 }
970 
971 // construct experiment filename & path
972 
980 void vpIoTools::addNameElement(const std::string &strTrue, const bool &cond, const std::string &strFalse)
981 {
982  if(cond)
983  baseName += "_" + strTrue;
984  else if(strFalse != "")
985  baseName += "_" + strFalse;
986 }
987 
995 void vpIoTools::addNameElement(const std::string &strTrue, const double &val)
996 {
997  //if(val != 0.)
998  if(std::fabs(val) < std::numeric_limits<double>::epsilon())
999  {
1000  char valC[256];
1001  sprintf(valC, "%.3f", val);
1002  std::string valS(valC);
1003  baseName += "_" + strTrue + valS;
1004  }
1005 }
1006 
1015 void vpIoTools::createBaseNamePath(const bool &empty)
1016 {
1017  if(vpIoTools::checkDirectory(baseDir + baseName) == false) {
1019  std::cout << "creating directory " + baseDir + baseName << std::endl;
1020  }
1021  else {
1022  if(empty) {
1023  std::cout << "emptying directory " + baseDir + baseName << std::endl;
1025  }
1026  }
1027 }
1028 
1035 void vpIoTools::saveConfigFile(const bool &actuallySave)
1036 {
1037  if(actuallySave) {
1038  std::string dest = baseDir + "/" + baseName + "_config.txt";
1039  // file copy
1040  vpIoTools::copy(configFile, dest);
1041  }
1042 }
#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:123
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 bool readConfigVar(const std::string &var, double &value)
Definition: vpIoTools.cpp:805
static void createBaseNamePath(const bool &empty=false)
Definition: vpIoTools.cpp:1015
static std::string baseDir
Definition: vpIoTools.h:229
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:1035
static std::vector< std::string > configVars
Definition: vpIoTools.h:231
static void loadConfigFile(const std::string &confFile)
Definition: vpIoTools.cpp:758
static std::string baseName
Definition: vpIoTools.h:228
static std::string configFile
Definition: vpIoTools.h:230
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:232
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:232
static void addNameElement(const std::string &strTrue, const bool &cond=true, const std::string &strFalse="")
Definition: vpIoTools.cpp:980