SystemTools.cxx 93.1 KB
Newer Older
1
2
3
4
5
/*=========================================================================

  Program:   KWSys - Kitware System Library
  Module:    SystemTools.cxx

Brad King's avatar
Brad King committed
6
7
  Copyright (c) Kitware, Inc., Insight Consortium.  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
8

Brad King's avatar
Brad King committed
9
10
     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11
12
13
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
14
15
#include "kwsysPrivate.h"
#include KWSYS_HEADER(SystemTools.hxx)
16
#include KWSYS_HEADER(Directory.hxx)
17

18
19
#include KWSYS_HEADER(ios/iostream)
#include KWSYS_HEADER(ios/fstream)
20
#include KWSYS_HEADER(ios/sstream)
21

22
23
24
25
26
27
28
29
30
31
// Work-around CMake dependency scanning limitation.  This must
// duplicate the above list of headers.
#if 0
# include "SystemTools.hxx.in"
# include "Directory.hxx.in"
# include "kwsys_ios_iostream.h.in"
# include "kwsys_ios_fstream.h.in"
# include "kwsys_ios_sstream.h.in"
#endif

32
33
34
35
#ifdef _MSC_VER
# pragma warning (disable: 4786)
#endif

36
37
38
#if defined(__sgi) && !defined(__GNUC__)
# pragma set woff 1375 /* base class destructor not virtual */
#endif
39

40
41
#include <ctype.h>
#include <errno.h>
42
43
#ifdef __QNX__
# include <malloc.h> /* for malloc/free on QNX */
44
#endif
45
46
47
48
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
49
50
51
52
53
54
55
#include <time.h>

// support for realpath call
#ifndef _WIN32
#include <limits.h>
#include <sys/param.h>
#include <sys/wait.h>
56
57
#include <sys/ioctl.h>
#include <unistd.h>
Andy Cedilnik's avatar
Andy Cedilnik committed
58
#include <termios.h>
59
60
#endif

61
62
63
64
65
// Windows API.  Some parts used even on cygwin.
#if defined(_WIN32)
# include <windows.h>
#endif

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// This is a hack to prevent warnings about these functions being
// declared but not referenced.
#if defined(__sgi) && !defined(__GNUC__)
# include <sys/termios.h>
namespace KWSYS_NAMESPACE
{
class SystemToolsHack
{
public:
  enum
  {
    Ref1 = sizeof(cfgetospeed(0)),
    Ref2 = sizeof(cfgetispeed(0)),
    Ref3 = sizeof(tcgetattr(0, 0)),
    Ref4 = sizeof(tcsetattr(0, 0, 0)),
    Ref5 = sizeof(cfsetospeed(0,0)),
    Ref6 = sizeof(cfsetispeed(0,0))
  };
};
}
#endif
87

88
#if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) ||defined(__BORLANDC__) || defined(__MINGW32__))
89
#include <io.h>
90
91
#include <direct.h>
#define _unlink unlink
92
93
94
95
96
97
98
99
100
101
#endif 

/* The maximum length of a file name.  */
#if defined(PATH_MAX)
# define KWSYS_SYSTEMTOOLS_MAXPATH PATH_MAX
#elif defined(MAXPATHLEN)
# define KWSYS_SYSTEMTOOLS_MAXPATH MAXPATHLEN
#else
# define KWSYS_SYSTEMTOOLS_MAXPATH 16384
#endif
102
103
104
105
106
107
108
#if defined(__WATCOMC__)
#include <direct.h>
#define _mkdir mkdir
#define _rmdir rmdir
#define _getcwd getcwd
#define _chdir chdir
#endif
109

110
#if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__)) 
111
112
113
114
inline int Mkdir(const char* dir)
{
  return _mkdir(dir);
}
115
116
117
118
inline int Rmdir(const char* dir)
{
  return _rmdir(dir);
}
119
120
121
122
123
124
125
126
127
128
129
130
inline const char* Getcwd(char* buf, unsigned int len)
{
  return _getcwd(buf, len);
}
inline int Chdir(const char* dir)
{
  #if defined(__BORLANDC__)
  return chdir(dir);
  #else
  return _chdir(dir);
  #endif
}
131
inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
132
133
134
135
136
{
  char *ptemp;
  char fullpath[MAX_PATH];
  if( GetFullPathName(path, sizeof(fullpath), fullpath, &ptemp) )
    {
137
138
    resolved_path = fullpath;
    KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
139
140
    }
}
141
142
143
144
145
146
147
148
#else
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
inline int Mkdir(const char* dir)
{
  return mkdir(dir, 00777);
}
149
150
151
152
inline int Rmdir(const char* dir)
{
  return rmdir(dir);
}
153
154
155
156
157
158
159
160
inline const char* Getcwd(char* buf, unsigned int len)
{
  return getcwd(buf, len);
}
inline int Chdir(const char* dir)
{
  return chdir(dir);
}
161
inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
162
{
163
  char resolved_name[KWSYS_SYSTEMTOOLS_MAXPATH];
164
165
166

  realpath(path, resolved_name);
  resolved_path = resolved_name;
167
}
168
169
#endif

170
171
172
173
174
175
176
177
178
179
180
181
#if !defined(_WIN32) && defined(__COMO__)
// Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE.
extern "C"
{
extern FILE *popen (__const char *__command, __const char *__modes) __THROW;
extern int pclose (FILE *__stream) __THROW;
extern char *realpath (__const char *__restrict __name,
                       char *__restrict __resolved) __THROW;
extern char *strdup (__const char *__s) __THROW;
extern int putenv (char *__string) __THROW;
}
#endif
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204

/* Implement floattime() for various platforms */
// Taken from Python 2.1.3

#if defined( _WIN32 ) && !defined( __CYGWIN__ )
#  include <sys/timeb.h>
#  define HAVE_FTIME
#  if defined( __BORLANDC__)
#    define FTIME ftime
#    define TIMEB timeb
#  else // Visual studio?
#    define FTIME _ftime
#    define TIMEB _timeb
#  endif
#elif defined( __CYGWIN__ ) || defined( __linux__ )
#  include <sys/time.h>
#  include <time.h>
#  define HAVE_GETTIMEOFDAY
#endif

namespace KWSYS_NAMESPACE
{

205
206
207
208
209
class SystemToolsTranslationMap : 
    public kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>
{
};

210

211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
double
SystemTools::GetTime(void)
{
  /* There are three ways to get the time:
     (1) gettimeofday() -- resolution in microseconds
     (2) ftime() -- resolution in milliseconds
     (3) time() -- resolution in seconds
     In all cases the return value is a float in seconds.
     Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
     fail, so we fall back on ftime() or time().
     Note: clock resolution does not imply clock accuracy! */
#ifdef HAVE_GETTIMEOFDAY
  {
  struct timeval t;
#ifdef GETTIMEOFDAY_NO_TZ
  if (gettimeofday(&t) == 0)
    return (double)t.tv_sec + t.tv_usec*0.000001;
#else /* !GETTIMEOFDAY_NO_TZ */
  if (gettimeofday(&t, (struct timezone *)NULL) == 0)
    return (double)t.tv_sec + t.tv_usec*0.000001;
#endif /* !GETTIMEOFDAY_NO_TZ */
  }
#endif /* !HAVE_GETTIMEOFDAY */
  {
#if defined(HAVE_FTIME)
  struct TIMEB t;
237
  ::FTIME(&t);
238
239
240
241
242
243
244
245
246
247
  return (double)t.time + (double)t.millitm * (double)0.001;
#else /* !HAVE_FTIME */
  time_t secs;
  time(&secs);
  return (double)secs;
#endif /* !HAVE_FTIME */
  }
}

// adds the elements of the env variable path to the arg passed in
248
void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char* env)
249
250
251
252
253
254
{
#if defined(_WIN32) && !defined(__CYGWIN__)
  const char* pathSep = ";";
#else
  const char* pathSep = ":";
#endif
255
256
257
258
  if(!env)
    {
    env = "PATH";
    }
259
260
261
262
263
264
265
266
  const char* cpathEnv = SystemTools::GetEnv(env);
  if ( !cpathEnv )
    {
    return;
    }

  kwsys_stl::string pathEnv = cpathEnv;
   
267
268
269
270
271
  // A hack to make the below algorithm work.  
  if(pathEnv[pathEnv.length()-1] != ':')
    {
    pathEnv += pathSep;
    }
272
  kwsys_stl::string::size_type start =0;
273
274
275
  bool done = false;
  while(!done)
    {
276
277
    kwsys_stl::string::size_type endpos = pathEnv.find(pathSep, start);
    if(endpos != kwsys_stl::string::npos)
278
279
280
281
282
283
284
285
286
      {
      path.push_back(pathEnv.substr(start, endpos-start));
      start = endpos+1;
      }
    else
      {
      done = true;
      }
    }
287
  for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
288
289
290
291
292
293
      i != path.end(); ++i)
    {
    SystemTools::ConvertToUnixSlashes(*i);
    }
}

Brad King's avatar
Brad King committed
294
295
296
297
298
const char* SystemTools::GetEnv(const char* key)
{
  return getenv(key);
}

299
bool SystemTools::GetEnv(const char* key, kwsys_stl::string& result)
Brad King's avatar
Brad King committed
300
301
302
303
304
305
306
307
308
309
310
311
{
  const char* v = getenv(key);
  if(v)
    {
    result = v;
    return true;
    }
  else
    {
    return false;
    }
}
312
313
314
315
316
317
318
319
320
321
322
323
324

const char* SystemTools::GetExecutableExtension()
{
#if defined(_WIN32) || defined(__CYGWIN__)
  return ".exe";
#else
  return "";
#endif  
}


bool SystemTools::MakeDirectory(const char* path)
{
325
326
  if(SystemTools::FileExists(path))
    {
327
    return true;
328
    }
329
  kwsys_stl::string dir = path;
330
331
332
333
334
335
  if(dir.size() == 0)
    {
    return false;
    }
  SystemTools::ConvertToUnixSlashes(dir);

336
337
  kwsys_stl::string::size_type pos = dir.find(':');
  if(pos == kwsys_stl::string::npos)
338
339
340
    {
    pos = 0;
    }
341
342
  kwsys_stl::string topdir;
  while((pos = dir.find('/', pos)) != kwsys_stl::string::npos)
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
    {
    topdir = dir.substr(0, pos);
    Mkdir(topdir.c_str());
    pos++;
    }
  if(dir[dir.size()-1] == '/')
    {
    topdir = dir.substr(0, dir.size());
    }
  else
    {
    topdir = dir;
    }
  if(Mkdir(topdir.c_str()) != 0)
    {
    // There is a bug in the Borland Run time library which makes MKDIR
    // return EACCES when it should return EEXISTS
    // if it is some other error besides directory exists
    // then return false
    if( (errno != EEXIST) 
#ifdef __BORLANDC__
        && (errno != EACCES) 
#endif      
      )
      {
      return false;
      }
    }
  return true;
}


// replace replace with with as many times as it shows up in source.
// write the result into source.
377
void SystemTools::ReplaceString(kwsys_stl::string& source,
378
379
380
                                   const char* replace,
                                   const char* with)
{
Ken Martin's avatar
Ken Martin committed
381
  const char *src = source.c_str();
Bill Lorensen's avatar
Bill Lorensen committed
382
  char *searchPos = const_cast<char *>(strstr(src,replace));
Ken Martin's avatar
Ken Martin committed
383
  
384
  // get out quick if string is not found
Ken Martin's avatar
Ken Martin committed
385
  if (!searchPos)
386
387
388
    {
    return;
    }
Ken Martin's avatar
Ken Martin committed
389
390
391
392
393
394
395
396

  // perform replacements until done
  size_t replaceSize = strlen(replace);
  char *orig = strdup(src);
  char *currentPos = orig;
  searchPos = searchPos - src + orig;
  
  // initialize the result
Ken Martin's avatar
Ken Martin committed
397
  source.erase(source.begin(),source.end());
Ken Martin's avatar
Ken Martin committed
398
  do
399
    {
Ken Martin's avatar
Ken Martin committed
400
401
402
403
    *searchPos = '\0';
    source += currentPos;
    currentPos = searchPos + replaceSize;
    // replace
404
    source += with;
Ken Martin's avatar
Ken Martin committed
405
    searchPos = strstr(currentPos,replace);
406
    }
Ken Martin's avatar
Ken Martin committed
407
408
409
410
411
  while (searchPos);

  // copy any trailing text
  source += currentPos;
  free(orig);
412
413
414
415
416
417
418
419
420
421
}

// Read a registry value.
// Example : 
//      HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
//      =>  will return the data of the "default" value of the key
//      HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
//      =>  will return the data of the "Root" value of the key

#if defined(_WIN32) && !defined(__CYGWIN__)
422
bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value)
423
424
{

425
426
427
  kwsys_stl::string primary = key;
  kwsys_stl::string second;
  kwsys_stl::string valuename;
428
429
 
  size_t start = primary.find("\\");
430
  if (start == kwsys_stl::string::npos)
431
432
433
434
435
    {
    return false;
    }

  size_t valuenamepos = primary.find(";");
436
  if (valuenamepos != kwsys_stl::string::npos)
437
438
439
440
441
442
443
    {
    valuename = primary.substr(valuenamepos+1);
    }

  second = primary.substr(start+1, valuenamepos-start-1);
  primary = primary.substr(0, start);
  
Bill Hoffman's avatar
Bill Hoffman committed
444
  HKEY primaryKey = HKEY_CURRENT_USER;
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
  if (primary == "HKEY_CURRENT_USER")
    {
    primaryKey = HKEY_CURRENT_USER;
    }
  if (primary == "HKEY_CURRENT_CONFIG")
    {
    primaryKey = HKEY_CURRENT_CONFIG;
    }
  if (primary == "HKEY_CLASSES_ROOT")
    {
    primaryKey = HKEY_CLASSES_ROOT;
    }
  if (primary == "HKEY_LOCAL_MACHINE")
    {
    primaryKey = HKEY_LOCAL_MACHINE;
    }
  if (primary == "HKEY_USERS")
    {
    primaryKey = HKEY_USERS;
    }
  
  HKEY hKey;
  if(RegOpenKeyEx(primaryKey, 
                  second.c_str(), 
                  0, 
                  KEY_READ, 
                  &hKey) != ERROR_SUCCESS)
    {
    return false;
    }
  else
    {
    DWORD dwType, dwSize;
    dwSize = 1023;
    char data[1024];
    if(RegQueryValueEx(hKey, 
                       (LPTSTR)valuename.c_str(), 
                       NULL, 
                       &dwType, 
                       (BYTE *)data, 
                       &dwSize) == ERROR_SUCCESS)
      {
      if (dwType == REG_SZ)
        {
        value = data;
490
        RegCloseKey(hKey);
491
492
493
494
495
496
497
        return true;
        }
      }
    }
  return false;
}
#else
498
bool SystemTools::ReadRegistryValue(const char *, kwsys_stl::string &)
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
{
  return false;
}
#endif


// Write a registry value.
// Example : 
//      HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
//      =>  will set the data of the "default" value of the key
//      HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
//      =>  will set the data of the "Root" value of the key

#if defined(_WIN32) && !defined(__CYGWIN__)
bool SystemTools::WriteRegistryValue(const char *key, const char *value)
{
515
516
517
  kwsys_stl::string primary = key;
  kwsys_stl::string second;
  kwsys_stl::string valuename;
518
519
 
  size_t start = primary.find("\\");
520
  if (start == kwsys_stl::string::npos)
521
522
523
524
525
    {
    return false;
    }

  size_t valuenamepos = primary.find(";");
526
  if (valuenamepos != kwsys_stl::string::npos)
527
528
529
530
531
532
533
    {
    valuename = primary.substr(valuenamepos+1);
    }

  second = primary.substr(start+1, valuenamepos-start-1);
  primary = primary.substr(0, start);
  
Bill Hoffman's avatar
Bill Hoffman committed
534
  HKEY primaryKey = HKEY_CURRENT_USER;
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
  if (primary == "HKEY_CURRENT_USER")
    {
    primaryKey = HKEY_CURRENT_USER;
    }
  if (primary == "HKEY_CURRENT_CONFIG")
    {
    primaryKey = HKEY_CURRENT_CONFIG;
    }
  if (primary == "HKEY_CLASSES_ROOT")
    {
    primaryKey = HKEY_CLASSES_ROOT;
    }
  if (primary == "HKEY_LOCAL_MACHINE")
    {
    primaryKey = HKEY_LOCAL_MACHINE;
    }
  if (primary == "HKEY_USERS")
    {
    primaryKey = HKEY_USERS;
    }
  
  HKEY hKey;
  DWORD dwDummy;
  if(RegCreateKeyEx(primaryKey, 
                    second.c_str(), 
                    0, 
                    "",
                    REG_OPTION_NON_VOLATILE,
                    KEY_WRITE,
                    NULL,
                    &hKey,
                    &dwDummy) != ERROR_SUCCESS)
    {
    return false;
    }

  if(RegSetValueEx(hKey, 
                   (LPTSTR)valuename.c_str(), 
                   0, 
                   REG_SZ, 
                   (CONST BYTE *)value, 
                   (DWORD)(strlen(value) + 1)) == ERROR_SUCCESS)
    {
    return true;
    }
  return false;
}
#else
bool SystemTools::WriteRegistryValue(const char *, const char *)
{
  return false;
}
#endif

// Delete a registry value.
// Example : 
//      HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
//      =>  will delete the data of the "default" value of the key
//      HKEY_LOCAL_MACHINE\SOFTWARE\Scriptics\Tcl\8.4;Root
//      =>  will delete  the data of the "Root" value of the key

#if defined(_WIN32) && !defined(__CYGWIN__)
bool SystemTools::DeleteRegistryValue(const char *key)
{
599
600
601
  kwsys_stl::string primary = key;
  kwsys_stl::string second;
  kwsys_stl::string valuename;
602
603
 
  size_t start = primary.find("\\");
604
  if (start == kwsys_stl::string::npos)
605
606
607
608
609
    {
    return false;
    }

  size_t valuenamepos = primary.find(";");
610
  if (valuenamepos != kwsys_stl::string::npos)
611
612
613
614
615
616
617
    {
    valuename = primary.substr(valuenamepos+1);
    }

  second = primary.substr(start+1, valuenamepos-start-1);
  primary = primary.substr(0, start);
  
Bill Hoffman's avatar
Bill Hoffman committed
618
  HKEY primaryKey = HKEY_CURRENT_USER;
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
  if (primary == "HKEY_CURRENT_USER")
    {
    primaryKey = HKEY_CURRENT_USER;
    }
  if (primary == "HKEY_CURRENT_CONFIG")
    {
    primaryKey = HKEY_CURRENT_CONFIG;
    }
  if (primary == "HKEY_CLASSES_ROOT")
    {
    primaryKey = HKEY_CLASSES_ROOT;
    }
  if (primary == "HKEY_LOCAL_MACHINE")
    {
    primaryKey = HKEY_LOCAL_MACHINE;
    }
  if (primary == "HKEY_USERS")
    {
    primaryKey = HKEY_USERS;
    }
  
  HKEY hKey;
  if(RegOpenKeyEx(primaryKey, 
                  second.c_str(), 
                  0, 
                  KEY_WRITE, 
                  &hKey) != ERROR_SUCCESS)
    {
    return false;
    }
  else
    {
    if(RegDeleteValue(hKey, 
                      (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
      {
654
      RegCloseKey(hKey);
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
      return true;
      }
    }
  return false;
}
#else
bool SystemTools::DeleteRegistryValue(const char *)
{
  return false;
}
#endif

bool SystemTools::SameFile(const char* file1, const char* file2)
{
#ifdef _WIN32
  HANDLE hFile1, hFile2;

  hFile1 = CreateFile( file1, 
                      GENERIC_READ, 
                      FILE_SHARE_READ ,
                      NULL,
                      OPEN_EXISTING,
                      FILE_FLAG_BACKUP_SEMANTICS,
                      NULL
    );
  hFile2 = CreateFile( file2, 
                      GENERIC_READ, 
                      FILE_SHARE_READ, 
                      NULL,
                      OPEN_EXISTING,
                      FILE_FLAG_BACKUP_SEMANTICS,
                      NULL
    );
  if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
    {
    if(hFile1 != INVALID_HANDLE_VALUE)
      {
      CloseHandle(hFile1);
      }
    if(hFile2 != INVALID_HANDLE_VALUE)
      {
      CloseHandle(hFile2);
      }
    return false;
    }

   BY_HANDLE_FILE_INFORMATION fiBuf1;
   BY_HANDLE_FILE_INFORMATION fiBuf2;
   GetFileInformationByHandle( hFile1, &fiBuf1 );
   GetFileInformationByHandle( hFile2, &fiBuf2 );
   CloseHandle(hFile1);
   CloseHandle(hFile2);
707
708
   return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
           fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
           fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
#else
  struct stat fileStat1, fileStat2;
  if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
    {
    // see if the files are the same file
    // check the device inode and size
    if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 && 
       memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
       fileStat2.st_size == fileStat1.st_size 
      ) 
      {
      return true;
      }
    }
  return false;
#endif
}


// return true if the file exists
bool SystemTools::FileExists(const char* filename)
{
732
733
#ifdef _MSC_VER
# define access _access
734
#endif
735
736
#ifndef R_OK
# define R_OK 04
737
#endif
738
  if ( access(filename, R_OK) != 0 )
739
740
741
742
743
744
745
746
747
748
    {
    return false;
    }
  else
    {
    return true;
    }
}


749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
bool SystemTools::FileTimeCompare(const char* f1, const char* f2,
                                  int* result)
{
  // Default to same time.
  *result = 0;
#if !defined(_WIN32) || defined(__CYGWIN__)
  // POSIX version.  Use stat function to get file modification time.
  struct stat s1;
  if(stat(f1, &s1) != 0)
    {
    return false;
    }
  struct stat s2;
  if(stat(f2, &s2) != 0)
    {
    return false;
    }
# if KWSYS_STAT_HAS_ST_MTIM
  // Compare using nanosecond resolution.
  if(s1.st_mtim.tv_sec < s2.st_mtim.tv_sec)
    {
    *result = -1;
    }
  else if(s1.st_mtim.tv_sec > s2.st_mtim.tv_sec)
    {
    *result = 1;
    }
  else if(s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec)
    {
    *result = -1;
    }
  else if(s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec)
    {
    *result = 1;
    }
# else
  // Compare using 1 second resolution.
  if(s1.st_mtime < s2.st_mtime)
    {
    *result = -1;
    }
  else if(s1.st_mtime > s2.st_mtime)
    {
    *result = 1;
    }
# endif
#else
796
797
798
799
  // Windows version.  Get the modification time from extended file attributes.
  WIN32_FILE_ATTRIBUTE_DATA f1d;
  WIN32_FILE_ATTRIBUTE_DATA f2d;
  if(!GetFileAttributesEx(f1, GetFileExInfoStandard, &f1d))
800
801
802
    {
    return false;
    }
803
  if(!GetFileAttributesEx(f2, GetFileExInfoStandard, &f2d))
804
805
806
807
808
    {
    return false;
    }

  // Compare the file times using resolution provided by system call.
809
  *result = (int)CompareFileTime(&f1d.ftLastWriteTime, &f2d.ftLastWriteTime);
810
811
812
813
814
#endif
  return true;
}


815
816
// Return a capitalized string (i.e the first letter is uppercased, all other
// are lowercased)
817
kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s)
818
{
819
  kwsys_stl::string n;
Bill Hoffman's avatar
Bill Hoffman committed
820
821
822
823
  if(s.size() == 0)
    {
    return n;
    }
824
  n.resize(s.size());
Bill Hoffman's avatar
Bill Hoffman committed
825
  n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0]));
826
827
  for (size_t i = 1; i < s.size(); i++)
    {
Bill Hoffman's avatar
Bill Hoffman committed
828
    n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
829
830
831
832
    }
  return n;
}

833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
// Return capitalized words
kwsys_stl::string SystemTools::CapitalizedWords(const kwsys_stl::string& s)
{
  kwsys_stl::string n(s);
  for (size_t i = 0; i < s.size(); i++)
    {
    if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
      {
      n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
      }
    }
  return n;
}

// Return uncapitalized words
kwsys_stl::string SystemTools::UnCapitalizedWords(const kwsys_stl::string& s)
{
  kwsys_stl::string n(s);
  for (size_t i = 0; i < s.size(); i++)
    {
    if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
      {
      n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
      }
    }
  return n;
}
860

861
862
863
864
865
866
867
868
869
870
871
872
873
874
kwsys_stl::string SystemTools::AddSpaceBetweenCapitalizedWords(
  const kwsys_stl::string& s)
{
  kwsys_stl::string n;
  if (s.size())
    {
    n.reserve(s.size());
    n += s[0];
    for (size_t i = 1; i < s.size(); i++)
      {
      if (isupper(s[i]) && !isspace(s[i - 1]) && !isupper(s[i - 1]))
        {
        n += ' ';
        }
Sebastien Barre's avatar
Sebastien Barre committed
875
      n += s[i];
876
877
878
879
880
      }
    }
  return n;
}

881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
char* SystemTools::AppendStrings(const char* str1, const char* str2)
{
  if (!str1)
    {
    return SystemTools::DuplicateString(str2);
    }
  if (!str2)
    {
    return SystemTools::DuplicateString(str1);
    }
  size_t len1 = strlen(str1);
  char *newstr = new char[len1 + strlen(str2) + 1];
  if (!newstr)
    {
    return 0;
    }
  strcpy(newstr, str1);
  strcat(newstr + len1, str2);
  return newstr;
}

char* SystemTools::AppendStrings(
  const char* str1, const char* str2, const char* str3)
{
  if (!str1)
    {
    return SystemTools::AppendStrings(str2, str3);
    }
  if (!str2)
    {
    return SystemTools::AppendStrings(str1, str3);
    }
  if (!str3)
    {
    return SystemTools::AppendStrings(str1, str2);
    }

  size_t len1 = strlen(str1), len2 = strlen(str2);
  char *newstr = new char[len1 + len2 + strlen(str3) + 1];
  if (!newstr)
    {
    return 0;
    }
  strcpy(newstr, str1);
  strcat(newstr + len1, str2);
  strcat(newstr + len1 + len2, str3);
  return newstr;
}

930
// Return a lower case string 
931
kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s)
932
{
933
  kwsys_stl::string n;
934
935
936
  n.resize(s.size());
  for (size_t i = 0; i < s.size(); i++)
    {
Bill Hoffman's avatar
Bill Hoffman committed
937
    n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
938
939
940
941
942
    }
  return n;
}

// Return a lower case string 
943
kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s)
944
{
945
  kwsys_stl::string n;
946
947
948
  n.resize(s.size());
  for (size_t i = 0; i < s.size(); i++)
    {
Bill Hoffman's avatar
Bill Hoffman committed
949
    n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
950
951
952
953
    }
  return n;
}

954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
// Count char in string
size_t SystemTools::CountChar(const char* str, char c)
{
  size_t count = 0;

  if (str)
    {
    while (*str)
      {
      if (*str == c)
        {
        ++count;
        }
      ++str;
      }
    }
  return count;
}

// Remove chars in string
char* SystemTools::RemoveChars(const char* str, const char *toremove)
{
  if (!str)
    {
    return NULL;
    }
  char *clean_str = new char [strlen(str) + 1];
  char *ptr = clean_str;
  while (*str)
    {
    const char *str2 = toremove;
    while (*str2 && *str != *str2)
      {
      ++str2;
      }
    if (!*str2)
      {
      *ptr++ = *str;
      }
    ++str;
    }
  *ptr = '\0';
  return clean_str;
}

// Remove chars in string
char* SystemTools::RemoveCharsButUpperHex(const char* str)
{
  if (!str)
    {
    return 0;
    }
  char *clean_str = new char [strlen(str) + 1];
  char *ptr = clean_str;
  while (*str)
    {
    if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'H'))
      {
      *ptr++ = *str;
      }
    ++str;
    }
  *ptr = '\0';
  return clean_str;
}

// Replace chars in string
char* SystemTools::ReplaceChars(char* str, const char *toreplace, char replacement)
{
  if (str)
    {
    char *ptr = str;
    while (*ptr)
      {
      const char *ptr2 = toreplace;
      while (*ptr2)
        {
        if (*ptr == *ptr2)
          {
          *ptr = replacement;
          }
        ++ptr2;
        }
      ++ptr;
      }
    }
  return str;
}

1043
// Returns if string starts with another string
1044
bool SystemTools::StringStartsWith(const char* str1, const char* str2)
1045
1046
1047
1048
1049
1050
{
  if (!str1 || !str2)
    {
    return false;
    }
  size_t len1 = strlen(str1), len2 = strlen(str2);
1051
  return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false;
1052
1053
1054
}

// Returns if string ends with another string
1055
bool SystemTools::StringEndsWith(const char* str1, const char* str2)
1056
1057
1058
1059
1060
1061
1062
1063
1064
{
  if (!str1 || !str2)
    {
    return false;
    }
  size_t len1 = strlen(str1), len2 = strlen(str2);
  return len1 >= len2 &&  !strncmp(str1 + (len1 - len2), str2, len2) ? true : false;
}

1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
// Returns a pointer to the last occurence of str2 in str1
const char* SystemTools::FindLastString(const char* str1, const char* str2)
{
  if (!str1 || !str2)
    {
    return NULL;
    }
  
  size_t len1 = strlen(str1), len2 = strlen(str2);
  if (len1 >= len2)
    {
    const char *ptr = str1 + len1 - len2;
    do
      {
      if (!strncmp(ptr, str2, len2))
        {
        return ptr;
        }
      } while (ptr-- != str1);
    }

  return NULL;
}

// Duplicate string
char* SystemTools::DuplicateString(const char* str)
{
  if (str)
    {
    char *newstr = new char [strlen(str) + 1];
    return strcpy(newstr, str);
    }
  return NULL;
}

1100
// Return a cropped string 
1101
1102
kwsys_stl::string SystemTools::CropString(const kwsys_stl::string& s, 
                                          size_t max_len)
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
{
  if (!s.size() || max_len == 0 || max_len >= s.size())
    {
    return s;
    }

  kwsys_stl::string n;
  n.reserve(max_len);

  size_t middle = max_len / 2;

  n += s.substr(0, middle);
  n += s.substr(s.size() - (max_len - middle), kwsys_stl::string::npos);

  if (max_len > 2)
    {
    n[middle] = '.';
    if (max_len > 3)
      {
      n[middle - 1] = '.';
      if (max_len > 4)
        {
        n[middle + 1] = '.';
        }
      }
    }

  return n;
}
1132

1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
//----------------------------------------------------------------------------
std::vector<kwsys::String> SystemTools::SplitString(const char* p, char sep, bool isPath)
{
  std::string path = p;
  std::vector<kwsys::String> paths;
  if(isPath && path[0] == '/')
    {
    path.erase(path.begin());
    paths.push_back("/"); 
    }
  std::string::size_type pos1 = 0;
  std::string::size_type pos2 = path.find(sep, pos1+1);
  while(pos2 != std::string::npos)
    {
    paths.push_back(path.substr(pos1, pos2-pos1));
    pos1 = pos2+1;
    pos2 = path.find(sep, pos1+1);
    } 
  paths.push_back(path.substr(pos1, pos2-pos1));
  
  return paths;
}

1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
//----------------------------------------------------------------------------
int SystemTools::EstimateFormatLength(const char *format, va_list ap)
{
  if (!format)
    {
    return 0;
    }

  // Quick-hack attempt at estimating the length of the string.
  // Should never under-estimate.
  
  // Start with the length of the format string itself.

  int length = strlen(format);
  
  // Increase the length for every argument in the format.

  const char* cur = format;
  while(*cur)
    {
    if(*cur++ == '%')
      {
      // Skip "%%" since it doesn't correspond to a va_arg.
      if(*cur != '%')
        {
        while(!int(isalpha(*cur)))
          {
          ++cur;
          }
        switch (*cur)
          {
          case 's':
          {
          // Check the length of the string.
          char* s = va_arg(ap, char*);
          if(s)
            {
            length += strlen(s);
            }
          } break;
          case 'e':
          case 'f':
          case 'g':
          {
          // Assume the argument contributes no more than 64 characters.
          length += 64;
            
          // Eat the argument.
          static_cast<void>(va_arg(ap, double));
          } break;
          default:
          {
          // Assume the argument contributes no more than 64 characters.
          length += 64;
            
          // Eat the argument.
          static_cast<void>(va_arg(ap, int));
          } break;
          }
        }
      
      // Move past the characters just tested.
      ++cur;
      }
    }
  
  return length;
}

1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
kwsys_stl::string SystemTools::EscapeChars(
  const char *str, 
  const char *chars_to_escape, 
  char escape_char)
{
  kwsys_stl::string n;
  if (str)
    {
    if (!chars_to_escape | !*chars_to_escape)
      {
      n.append(str);
      }
    else
      {
      n.reserve(strlen(str));
      while (*str)
        {
        const char *ptr = chars_to_escape;
        while (*ptr)
          {
          if (*str == *ptr)
            {
            n += escape_char;
            break;
            }
          ++ptr;
          }
        n += *str;
        ++str;
        }
      }
    }
  return n;
}

1260
// convert windows slashes to unix slashes 
1261
void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path)
1262
{
Andy Cedilnik's avatar
Andy Cedilnik committed
1263
1264
1265
1266
1267
  const char* pathCString = path.c_str();
  bool hasDoubleSlash = false;

  const char* pos0 = pathCString;
  const char* pos1 = pathCString+1;
1268
  for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos )
1269
    {
1270
    // make sure we don't convert an escaped space to a unix slash
Andy Cedilnik's avatar
Andy Cedilnik committed
1271
    if ( *pos0 == '\\' && *pos1 != ' ' )
1272
      {
Andy Cedilnik's avatar
Andy Cedilnik committed
1273
      path[pos] = '/';
1274
      }
1275

Andy Cedilnik's avatar
Andy Cedilnik committed
1276
1277
1278
1279
    // Also, reuse the loop to check for slash followed by another slash
    if ( !hasDoubleSlash && *pos1 &&
      *pos1 == '/' && *(pos1+1) == '/' )
      {
1280
#ifdef _WIN32
Andy Cedilnik's avatar
Andy Cedilnik committed
1281
1282
1283
1284
1285
1286
      // However, on windows if the first characters are both slashes,
      // then keep them that way, so that network paths can be handled.
      if ( pos > 0)
        {
        hasDoubleSlash = true;
        }
Ken Martin's avatar
Ken Martin committed
1287
#else
Andy Cedilnik's avatar
Andy Cedilnik committed
1288
      hasDoubleSlash = true;
1289
#endif
Andy Cedilnik's avatar
Andy Cedilnik committed
1290
      }
1291

Andy Cedilnik's avatar
Andy Cedilnik committed
1292
1293
1294
1295
1296
    pos0 ++;
    pos1 ++;
    }

  if ( hasDoubleSlash )
1297
1298
1299
1300
1301
    {
    SystemTools::ReplaceString(path, "//", "/");
    }
  
  // remove any trailing slash
Andy Cedilnik's avatar
Andy Cedilnik committed
1302
  if(!path.empty())
1303
    {
Andy Cedilnik's avatar
Andy Cedilnik committed
1304
    // if there is a tilda ~ then replace it with HOME
1305
    pathCString = path.c_str();
Andy Cedilnik's avatar
Andy Cedilnik committed
1306
1307
1308
1309
1310
1311
1312
1313
    if(*pathCString == '~')
      {
      const char* homeEnv = SystemTools::GetEnv("HOME");
      if (homeEnv)
        {
        path.replace(0,1,homeEnv);
        }
      }
1314

1315
    pathCString = path.c_str();
Andy Cedilnik's avatar
Andy Cedilnik committed
1316
    if (*(pathCString+(path.size()-1)) == '/')
1317
      {
Andy Cedilnik's avatar
Andy Cedilnik committed
1318
      path = path.substr(0, path.size()-1);
1319
      }
Andy Cedilnik's avatar
Andy Cedilnik committed
1320

1321
1322
1323
1324
    }
}

// change // to /, and escape any spaces in the path
1325
kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path)
1326
{
1327
  kwsys_stl::string ret = path;
1328
1329
  
  // remove // except at the beginning might be a cygwin drive
1330
  kwsys_stl::string::size_type pos=0;
1331
  while((pos = ret.find("//", pos)) != kwsys_stl::string::npos)
1332
1333
1334
1335
    {
    ret.erase(pos, 1);
    }
  // now escape spaces if there is a space in the path
1336
  if(ret.find(" ") != kwsys_stl::string::npos)
1337
    {
1338
    kwsys_stl::string result = "";
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
    char lastch = 1;
    for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
      {
        // if it is already escaped then don't try to escape it again
      if(*ch == ' ' && lastch != '\\')
        {
        result += '\\';
        }
      result += *ch;
      lastch = *ch;
      }
    ret = result;
    }
  return ret;
}

1355
kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
1356
1357
1358
1359
1360
1361
1362
1363
1364
{
#if defined(_WIN32) && !defined(__CYGWIN__)
  return SystemTools::ConvertToWindowsOutputPath(path);
#else
  return SystemTools::ConvertToUnixOutputPath(path);
#endif
}

// remove double slashes not at the start
1365
kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
1366
{  
1367
1368
1369
1370
1371
  kwsys_stl::string ret;
  // make it big enough for all of path and double quotes
  ret.reserve(strlen(path)+3);
  // put path into the string
  ret.insert(0,path);
1372
  kwsys_stl::string::size_type pos = 0;
1373
  // first convert all of the slashes
1374
  while((pos = ret.find('/', pos)) != kwsys_stl::string::npos)
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
    {
    ret[pos] = '\\';
    pos++;
    }
  // check for really small paths
  if(ret.size() < 2)
    {
    return ret;
    }
  // now clean up a bit and remove double slashes
  // Only if it is not the first position in the path which is a network
  // path on windows
  pos = 1; // start at position 1
  if(ret[0] == '\"')
    {
    pos = 2;  // if the string is already quoted then start at 2
    if(ret.size() < 3)
      {
      return ret;
      }
    }
1396
  while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos)
1397
1398
1399
1400
1401
    {
    ret.erase(pos, 1);
    }
  // now double quote the path if it has spaces in it
  // and is not already double quoted
1402
  if(ret.find(' ') != kwsys_stl::string::npos
1403
1404
     && ret[0] != '\"')
    {
Bill Hoffman's avatar
Bill Hoffman committed
1405
1406
    ret.insert(static_cast<kwsys_stl::string::size_type>(0),
               static_cast<kwsys_stl::string::size_type>(1), '\"');
1407
    ret.append(1, '\"');
1408
1409
1410
1411
1412
    }
  return ret;
}

bool SystemTools::CopyFileIfDifferent(const char* source,
1413
                                      const char* destination)
1414
1415
1416
{
  if(SystemTools::FilesDiffer(source, destination))
    {
1417
    return SystemTools::CopyFileAlways(source, destination);
1418
    }
1419
  return true;
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
}

  
bool SystemTools::FilesDiffer(const char* source,
                                const char* destination)
{
  struct stat statSource;
  if (stat(source, &statSource) != 0) 
    {
    return true;
    }

  struct stat statDestination;
  if (stat(destination, &statDestination) != 0) 
    {
    return true;
    }

  if(statSource.st_size != statDestination.st_size)
    {
    return true;
    }

  if(statSource.st_size == 0)
    {
    return false;
    }

#if defined(_WIN32) || defined(__CYGWIN__)
1449
1450
1451
1452
  kwsys_ios::ifstream finSource(source, (kwsys_ios::ios::binary |
                                         kwsys_ios::ios::in));
  kwsys_ios::ifstream finDestination(destination, (kwsys_ios::ios::binary |
                                                   kwsys_ios::ios::in));
1453
#else
1454
1455
  kwsys_ios::ifstream finSource(source);
  kwsys_ios::ifstream finDestination(destination);
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
#endif
  if(!finSource || !finDestination)
    {
    return true;
    }

  char* source_buf = new char[statSource.st_size];
  char* dest_buf = new char[statSource.st_size];

  finSource.read(source_buf, statSource.st_size);
  finDestination.read(dest_buf, statSource.st_size);

  if(statSource.st_size != static_cast<long>(finSource.gcount()) ||
     statSource.st_size != static_cast<long>(finDestination.gcount()))
    {
    // Failed to read files.
    delete [] source_buf;
    delete [] dest_buf;
    return true;
    }
  int ret = memcmp((const void*)source_buf, 
                   (const void*)dest_buf, 
                   statSource.st_size);

  delete [] dest_buf;
  delete [] source_buf;

  return ret != 0;
}


/**
 * Copy a file named by "source" to the file named by "destination".
 */
bool SystemTools::CopyFileAlways(const char* source, const char* destination)
{
1492
1493
1494
1495
1496
  // If files are the same do not copy
  if ( SystemTools::SameFile(source, destination) )
    {
    return true;
    }
1497
1498
1499
1500

  mode_t perm = 0;
  bool perms = SystemTools::GetPermissions(source, perm);

1501
1502
1503
1504
1505
1506
  const int bufferSize = 4096;
  char buffer[bufferSize];

  // If destination is a directory, try to create a file with the same
  // name as the source in that directory.

1507
  kwsys_stl::string new_destination;
1508
1509
1510
1511
1512
1513
  if(SystemTools::FileExists(destination) &&
     SystemTools::FileIsDirectory(destination))
    {
    new_destination = destination;
    SystemTools::ConvertToUnixSlashes(new_destination);
    new_destination += '/';
1514
    kwsys_stl::string source_name = source;
1515
1516
1517
1518
1519
1520
    new_destination += SystemTools::GetFilenameName(source_name);
    destination = new_destination.c_str();
    }

  // Create destination directory

1521
  kwsys_stl::string destination_dir = destination;
1522
1523
1524
1525
1526
1527
  destination_dir = SystemTools::GetFilenamePath(destination_dir);
  SystemTools::MakeDirectory(destination_dir.c_str());

  // Open files

#if defined(_WIN32) || defined(__CYGWIN__)
1528
1529
  kwsys_ios::ifstream fin(source, 
                    kwsys_ios::ios::binary | kwsys_ios::ios::in);
1530
#else
1531
  kwsys_ios::ifstream fin(source);
1532
1533
1534
1535
1536
#endif
  if(!fin)
    {
    return false;
    }
1537
1538
1539
1540
1541
1542
 
  // try and remove the destination file so that read only destination files
  // can be written to.
  // If the remove fails continue so that files in read only directories
  // that do not allow file removal can be modified.
  SystemTools::RemoveFile(destination);
1543

1544
#if defined(_WIN32) || defined(__CYGWIN__)
1545
1546
  kwsys_ios::ofstream fout(destination, 
                     kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc);
1547
#else
1548
1549
  kwsys_ios::ofstream fout(destination, 
                     kwsys_ios::ios::out | kwsys_ios::ios::trunc);
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
#endif
  if(!fout)
    {
    return false;
    }
  
  // This copy loop is very sensitive on certain platforms with
  // slightly broken stream libraries (like HPUX).  Normally, it is
  // incorrect to not check the error condition on the fin.read()
  // before using the data, but the fin.gcount() will be zero if an
  // error occurred.  Therefore, the loop should be safe everywhere.
  while(fin)
    {
    fin.read(buffer, bufferSize);
    if(fin.gcount())
      {
      fout.write(buffer, fin.gcount());
      }
    }
  
  // Make sure the operating system has finished writing the file
  // before closing it.  This will ensure the file is finished before
  // the check below.
  fout.flush();
  
  fin.close();
  fout.close();

  // More checks.
  struct stat statSource, statDestination;
  statSource.st_size = 12345;
  statDestination.st_size = 12345;
  if(stat(source, &statSource) != 0)
    {
    return false;
    }
  else if(stat(destination, &statDestination) != 0)
    {
    return false;
    }
  else if(statSource.st_size != statDestination.st_size)
    {
    return false;
    }
1594
1595
1596
1597
1598
1599
1600
  if ( perms )
    {
    if ( !SystemTools::SetPermissions(destination, perm) )
      {
      return false;
      }
    }
1601
1602
1603
  return true;
}

1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
/**
 * Copy a directory content from "source" directory to the directory named by
 * "destination".
 */
bool SystemTools::CopyADirectory(const char* source, const char* destination)
{
  Directory dir;
  dir.Load(source);
  size_t fileNum;
  if ( !SystemTools::MakeDirectory(destination) )
    {
    return false;
    }
  for (fileNum = 0; fileNum <  dir.GetNumberOfFiles(); ++fileNum)
    {
    if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
        strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
      {
      kwsys_stl::string fullPath = source;
      fullPath += "/";
      fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
      if(SystemTools::FileIsDirectory(fullPath.c_str()))
        {
        kwsys_stl::string fullDestPath = destination;
        fullDestPath += "/";
        fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum));
        if (!SystemTools::CopyADirectory(fullPath.c_str(), fullDestPath.c_str()))
          {
          return false;
          }
        }
      else
        {
        if(!SystemTools::CopyFileAlways(fullPath.c_str(), destination))
          {
          return false;
          }
        }
      }
    }

  return true;
}


1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
// return size of file; also returns zero if no file exists
unsigned long SystemTools::FileLength(const char* filename)
{
  struct stat fs;
  if (stat(filename, &fs) != 0) 
    {
      return 0;
    }
  else
    {
Sebastien Barre's avatar
Sebastien Barre committed
1659
      return static_cast<unsigned long>(fs.st_size);
1660
1661
1662
1663
1664
    }
}

int SystemTools::Strucmp(const char *s1, const char *s2)
{
1665
1666
// lifted from Graphvis http://www.graphviz.org 
  while ((*s1 != '\0') 
1667
         && (tolower(*s1) == tolower(*s2)))
1668
1669
1670
1671
1672
    {
      s1++;
      s2++;
    }
 
1673
  return tolower(*s1) - tolower(*s2);
1674

1675
1676
}

1677
// return file's modified time
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
long int SystemTools::ModifiedTime(const char* filename)
{
  struct stat fs;
  if (stat(filename, &fs) != 0) 
    {
    return 0;
    }
  else
    {
    return (long int)fs.st_mtime;
    }
}

1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
// return file's creation time
long int SystemTools::CreationTime(const char* filename)
{
  struct stat fs;
  if (stat(filename, &fs) != 0) 
    {
    return 0;
    }
  else
    {
    return fs.st_ctime >= 0 ? (long int)fs.st_ctime : 0;
    }
}
1704

1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775