SystemTools.cxx 96.9 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
inline const char* Getcwd(char* buf, unsigned int len)
{
121
122
123
124
125
126
127
  const char* ret = _getcwd(buf, len);
  if(!ret)
    {
    fprintf(stderr, "No current working directory.\n");
    abort();
    }
  return ret;
128
129
130
131
132
133
134
135
136
}
inline int Chdir(const char* dir)
{
  #if defined(__BORLANDC__)
  return chdir(dir);
  #else
  return _chdir(dir);
  #endif
}
137
inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
138
139
140
141
142
{
  char *ptemp;
  char fullpath[MAX_PATH];
  if( GetFullPathName(path, sizeof(fullpath), fullpath, &ptemp) )
    {
143
144
    resolved_path = fullpath;
    KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
145
146
    }
}
147
148
149
150
151
152
153
154
#else
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
inline int Mkdir(const char* dir)
{
  return mkdir(dir, 00777);
}
155
156
157
158
inline int Rmdir(const char* dir)
{
  return rmdir(dir);
}
159
160
inline const char* Getcwd(char* buf, unsigned int len)
{
161
162
163
164
165
166
167
  const char* ret = getcwd(buf, len);
  if(!ret)
    {
    fprintf(stderr, "No current working directory\n");
    abort();
    }
  return ret;
168
}
169

170
171
172
173
inline int Chdir(const char* dir)
{
  return chdir(dir);
}
174
inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
175
{
176
  char resolved_name[KWSYS_SYSTEMTOOLS_MAXPATH];
177
178
179

  realpath(path, resolved_name);
  resolved_path = resolved_name;
180
}
181
182
#endif

183
184
185
186
187
188
189
190
191
192
193
194
#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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217

/* 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
{

218
219
220
221
222
class SystemToolsTranslationMap : 
    public kwsys_stl::map<kwsys_stl::string,kwsys_stl::string>
{
};

223

224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
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;
250
  ::FTIME(&t);
251
252
253
254
255
256
257
258
259
260
  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
261
void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char* env)
262
263
264
265
266
267
{
#if defined(_WIN32) && !defined(__CYGWIN__)
  const char* pathSep = ";";
#else
  const char* pathSep = ":";
#endif
268
269
270
271
  if(!env)
    {
    env = "PATH";
    }
272
273
274
275
276
277
278
  const char* cpathEnv = SystemTools::GetEnv(env);
  if ( !cpathEnv )
    {
    return;
    }

  kwsys_stl::string pathEnv = cpathEnv;
279
280

  // A hack to make the below algorithm work.
281
282
283
284
  if(pathEnv[pathEnv.length()-1] != ':')
    {
    pathEnv += pathSep;
    }
285
  kwsys_stl::string::size_type start =0;
286
287
288
  bool done = false;
  while(!done)
    {
289
290
    kwsys_stl::string::size_type endpos = pathEnv.find(pathSep, start);
    if(endpos != kwsys_stl::string::npos)
291
292
293
294
295
296
297
298
299
      {
      path.push_back(pathEnv.substr(start, endpos-start));
      start = endpos+1;
      }
    else
      {
      done = true;
      }
    }
300
  for(kwsys_stl::vector<kwsys_stl::string>::iterator i = path.begin();
301
302
303
304
305
306
      i != path.end(); ++i)
    {
    SystemTools::ConvertToUnixSlashes(*i);
    }
}

Brad King's avatar
Brad King committed
307
308
309
310
311
const char* SystemTools::GetEnv(const char* key)
{
  return getenv(key);
}

312
bool SystemTools::GetEnv(const char* key, kwsys_stl::string& result)
Brad King's avatar
Brad King committed
313
314
315
316
317
318
319
320
321
322
323
324
{
  const char* v = getenv(key);
  if(v)
    {
    result = v;
    return true;
    }
  else
    {
    return false;
    }
}
325
326
327
328
329
330
331
332
333
334
335
336
337

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


bool SystemTools::MakeDirectory(const char* path)
{
338
339
  if(SystemTools::FileExists(path))
    {
340
    return true;
341
    }
342
  kwsys_stl::string dir = path;
343
344
345
346
347
348
  if(dir.size() == 0)
    {
    return false;
    }
  SystemTools::ConvertToUnixSlashes(dir);

349
350
  kwsys_stl::string::size_type pos = dir.find(':');
  if(pos == kwsys_stl::string::npos)
351
352
353
    {
    pos = 0;
    }
354
355
  kwsys_stl::string topdir;
  while((pos = dir.find('/', pos)) != kwsys_stl::string::npos)
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
    {
    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
375
    if( (errno != EEXIST)
376
#ifdef __BORLANDC__
377
378
        && (errno != EACCES)
#endif
379
380
381
382
383
384
385
386
387
388
389
      )
      {
      return false;
      }
    }
  return true;
}


// replace replace with with as many times as it shows up in source.
// write the result into source.
390
void SystemTools::ReplaceString(kwsys_stl::string& source,
391
392
393
                                   const char* replace,
                                   const char* with)
{
Ken Martin's avatar
Ken Martin committed
394
  const char *src = source.c_str();
Bill Lorensen's avatar
Bill Lorensen committed
395
  char *searchPos = const_cast<char *>(strstr(src,replace));
Ken Martin's avatar
Ken Martin committed
396
  
397
  // get out quick if string is not found
Ken Martin's avatar
Ken Martin committed
398
  if (!searchPos)
399
400
401
    {
    return;
    }
Ken Martin's avatar
Ken Martin committed
402
403
404
405
406
407
408
409

  // 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
410
  source.erase(source.begin(),source.end());
Ken Martin's avatar
Ken Martin committed
411
  do
412
    {
Ken Martin's avatar
Ken Martin committed
413
414
415
416
    *searchPos = '\0';
    source += currentPos;
    currentPos = searchPos + replaceSize;
    // replace
417
    source += with;
Ken Martin's avatar
Ken Martin committed
418
    searchPos = strstr(currentPos,replace);
419
    }
Ken Martin's avatar
Ken Martin committed
420
421
422
423
424
  while (searchPos);

  // copy any trailing text
  source += currentPos;
  free(orig);
425
426
427
428
429
430
431
432
433
434
}

// 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__)
435
bool SystemTools::ReadRegistryValue(const char *key, kwsys_stl::string &value)
436
437
{

438
439
440
  kwsys_stl::string primary = key;
  kwsys_stl::string second;
  kwsys_stl::string valuename;
441
442
 
  size_t start = primary.find("\\");
443
  if (start == kwsys_stl::string::npos)
444
445
446
447
448
    {
    return false;
    }

  size_t valuenamepos = primary.find(";");
449
  if (valuenamepos != kwsys_stl::string::npos)
450
451
452
453
454
455
456
    {
    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
457
  HKEY primaryKey = HKEY_CURRENT_USER;
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
490
491
492
493
494
495
496
497
498
499
500
501
502
  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;
503
        RegCloseKey(hKey);
504
505
506
507
508
509
510
        return true;
        }
      }
    }
  return false;
}
#else
511
bool SystemTools::ReadRegistryValue(const char *, kwsys_stl::string &)
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
{
  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)
{
528
529
530
  kwsys_stl::string primary = key;
  kwsys_stl::string second;
  kwsys_stl::string valuename;
531
532
 
  size_t start = primary.find("\\");
533
  if (start == kwsys_stl::string::npos)
534
535
536
537
538
    {
    return false;
    }

  size_t valuenamepos = primary.find(";");
539
  if (valuenamepos != kwsys_stl::string::npos)
540
541
542
543
544
545
546
    {
    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
547
  HKEY primaryKey = HKEY_CURRENT_USER;
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
599
600
601
602
603
604
605
606
607
608
609
610
611
  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)
{
612
613
614
  kwsys_stl::string primary = key;
  kwsys_stl::string second;
  kwsys_stl::string valuename;
615
616
 
  size_t start = primary.find("\\");
617
  if (start == kwsys_stl::string::npos)
618
619
620
621
622
    {
    return false;
    }

  size_t valuenamepos = primary.find(";");
623
  if (valuenamepos != kwsys_stl::string::npos)
624
625
626
627
628
629
630
    {
    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
631
  HKEY primaryKey = HKEY_CURRENT_USER;
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
  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)
      {
667
      RegCloseKey(hKey);
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
707
708
709
710
711
712
713
714
715
716
717
718
719
      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);
720
721
   return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
           fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
           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)
{
745
746
#ifdef _MSC_VER
# define access _access
747
#endif
748
749
#ifndef R_OK
# define R_OK 04
750
#endif
751
  if ( access(filename, R_OK) != 0 )
752
753
754
755
756
757
758
759
760
761
    {
    return false;
    }
  else
    {
    return true;
    }
}


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
796
797
798
799
800
801
802
803
804
805
806
807
808
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
809
810
811
812
  // 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))
813
814
815
    {
    return false;
    }
816
  if(!GetFileAttributesEx(f2, GetFileExInfoStandard, &f2d))
817
818
819
820
821
    {
    return false;
    }

  // Compare the file times using resolution provided by system call.
822
  *result = (int)CompareFileTime(&f1d.ftLastWriteTime, &f2d.ftLastWriteTime);
823
824
825
826
827
#endif
  return true;
}


828
829
// Return a capitalized string (i.e the first letter is uppercased, all other
// are lowercased)
830
kwsys_stl::string SystemTools::Capitalized(const kwsys_stl::string& s)
831
{
832
  kwsys_stl::string n;
Bill Hoffman's avatar
Bill Hoffman committed
833
834
835
836
  if(s.size() == 0)
    {
    return n;
    }
837
  n.resize(s.size());
Bill Hoffman's avatar
Bill Hoffman committed
838
  n[0] = static_cast<kwsys_stl::string::value_type>(toupper(s[0]));
839
840
  for (size_t i = 1; i < s.size(); i++)
    {
Bill Hoffman's avatar
Bill Hoffman committed
841
    n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
842
843
844
845
    }
  return n;
}

846
847
848
849
850
851
// 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++)
    {
852
853
854
855
856
857
#if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
    // MS has an assert that will fail if s[i] < 0; setting
    // LC_CTYPE using setlocale() does *not* help. Painful.
    if ((int)s[i] >= 0 && isalpha(s[i]) && 
        (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
#else
858
    if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
859
#endif        
860
861
862
863
864
865
866
867
868
869
870
871
872
      {
      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++)
    {
873
874
875
876
877
878
#if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
    // MS has an assert that will fail if s[i] < 0; setting
    // LC_CTYPE using setlocale() does *not* help. Painful.
    if ((int)s[i] >= 0 && isalpha(s[i]) && 
        (i == 0 || ((int)s[i - 1] >= 0 && isspace(s[i - 1]))))
#else
879
    if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
880
#endif        
881
882
883
884
885
886
      {
      n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
      }
    }
  return n;
}
887

888
889
890
891
892
893
894
895
896
897
898
899
900
901
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
902
      n += s[i];
903
904
905
906
907
      }
    }
  return n;
}

908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
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;
}

957
// Return a lower case string 
958
kwsys_stl::string SystemTools::LowerCase(const kwsys_stl::string& s)
959
{
960
  kwsys_stl::string n;
961
962
963
  n.resize(s.size());
  for (size_t i = 0; i < s.size(); i++)
    {
Bill Hoffman's avatar
Bill Hoffman committed
964
    n[i] = static_cast<kwsys_stl::string::value_type>(tolower(s[i]));
965
966
967
968
969
    }
  return n;
}

// Return a lower case string 
970
kwsys_stl::string SystemTools::UpperCase(const kwsys_stl::string& s)
971
{
972
  kwsys_stl::string n;
973
974
975
  n.resize(s.size());
  for (size_t i = 0; i < s.size(); i++)
    {
Bill Hoffman's avatar
Bill Hoffman committed
976
    n[i] = static_cast<kwsys_stl::string::value_type>(toupper(s[i]));
977
978
979
980
    }
  return n;
}

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
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
// 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;
}

1070
// Returns if string starts with another string
1071
bool SystemTools::StringStartsWith(const char* str1, const char* str2)
1072
1073
1074
1075
1076
1077
{
  if (!str1 || !str2)
    {
    return false;
    }
  size_t len1 = strlen(str1), len2 = strlen(str2);
1078
  return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false;
1079
1080
1081
}

// Returns if string ends with another string
1082
bool SystemTools::StringEndsWith(const char* str1, const char* str2)
1083
1084
1085
1086
1087
1088
1089
1090
1091
{
  if (!str1 || !str2)
    {
    return false;
    }
  size_t len1 = strlen(str1), len2 = strlen(str2);
  return len1 >= len2 &&  !strncmp(str1 + (len1 - len2), str2, len2) ? true : false;
}

1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
// 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;
}

1127
// Return a cropped string 
1128
1129
kwsys_stl::string SystemTools::CropString(const kwsys_stl::string& s, 
                                          size_t max_len)
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
{
  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;
}
1159

1160
//----------------------------------------------------------------------------
1161
kwsys_stl::vector<kwsys::String> SystemTools::SplitString(const char* p, char sep, bool isPath)
1162
{
1163
1164
  kwsys_stl::string path = p;
  kwsys_stl::vector<kwsys::String> paths;
1165
1166
1167
1168
1169
  if(isPath && path[0] == '/')
    {
    path.erase(path.begin());
    paths.push_back("/"); 
    }
1170
1171
1172
  kwsys_stl::string::size_type pos1 = 0;
  kwsys_stl::string::size_type pos2 = path.find(sep, pos1+1);
  while(pos2 != kwsys_stl::string::npos)
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
    {
    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;
}

1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
//----------------------------------------------------------------------------
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.

1196
  size_t length = strlen(format);
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
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
  
  // 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;
      }
    }
  
1249
  return (int)length;
1250
1251
}

1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
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;
}

1287
// convert windows slashes to unix slashes 
1288
void SystemTools::ConvertToUnixSlashes(kwsys_stl::string& path)
1289
{
Andy Cedilnik's avatar
Andy Cedilnik committed
1290
1291
1292
1293
1294
  const char* pathCString = path.c_str();
  bool hasDoubleSlash = false;

  const char* pos0 = pathCString;
  const char* pos1 = pathCString+1;
1295
  for (kwsys_stl::string::size_type pos = 0; *pos0; ++ pos )
1296
    {
1297
    // make sure we don't convert an escaped space to a unix slash
Andy Cedilnik's avatar
Andy Cedilnik committed
1298
    if ( *pos0 == '\\' && *pos1 != ' ' )
1299
      {
Andy Cedilnik's avatar
Andy Cedilnik committed
1300
      path[pos] = '/';
1301
      }
1302

Andy Cedilnik's avatar
Andy Cedilnik committed
1303
1304
1305
1306
    // Also, reuse the loop to check for slash followed by another slash
    if ( !hasDoubleSlash && *pos1 &&
      *pos1 == '/' && *(pos1+1) == '/' )
      {
1307
#ifdef _WIN32
Andy Cedilnik's avatar
Andy Cedilnik committed
1308
1309
1310
1311
1312
1313
      // 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
1314
#else
Andy Cedilnik's avatar
Andy Cedilnik committed
1315
      hasDoubleSlash = true;
1316
#endif
Andy Cedilnik's avatar
Andy Cedilnik committed
1317
      }
1318

Andy Cedilnik's avatar
Andy Cedilnik committed
1319
1320
1321
1322
1323
    pos0 ++;
    pos1 ++;
    }

  if ( hasDoubleSlash )
1324
1325
1326
1327
1328
    {
    SystemTools::ReplaceString(path, "//", "/");
    }
  
  // remove any trailing slash
Andy Cedilnik's avatar
Andy Cedilnik committed
1329
  if(!path.empty())
1330
    {
Andy Cedilnik's avatar
Andy Cedilnik committed
1331
    // if there is a tilda ~ then replace it with HOME
1332
    pathCString = path.c_str();
Andy Cedilnik's avatar
Andy Cedilnik committed
1333
1334
1335
1336
1337
1338
1339
1340
    if(*pathCString == '~')
      {
      const char* homeEnv = SystemTools::GetEnv("HOME");
      if (homeEnv)
        {
        path.replace(0,1,homeEnv);
        }
      }
1341

1342
    pathCString = path.c_str();
Andy Cedilnik's avatar
Andy Cedilnik committed
1343
    if (*(pathCString+(path.size()-1)) == '/')
1344
      {
Andy Cedilnik's avatar
Andy Cedilnik committed
1345
      path = path.substr(0, path.size()-1);
1346
      }
Andy Cedilnik's avatar
Andy Cedilnik committed
1347

1348
1349
1350
1351
    }
}

// change // to /, and escape any spaces in the path
1352
kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path)
1353
{
1354
  kwsys_stl::string ret = path;
1355
1356
  
  // remove // except at the beginning might be a cygwin drive
1357
  kwsys_stl::string::size_type pos=0;
1358
  while((pos = ret.find("//", pos)) != kwsys_stl::string::npos)
1359
1360
1361
1362
    {
    ret.erase(pos, 1);
    }
  // now escape spaces if there is a space in the path
1363
  if(ret.find(" ") != kwsys_stl::string::npos)
1364
    {
1365
    kwsys_stl::string result = "";
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
    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;
}

1382
kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
1383
1384
1385
1386
1387
1388
1389
1390
1391
{
#if defined(_WIN32) && !defined(__CYGWIN__)
  return SystemTools::ConvertToWindowsOutputPath(path);
#else
  return SystemTools::ConvertToUnixOutputPath(path);
#endif
}

// remove double slashes not at the start
1392
kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
1393
{  
1394
1395
1396
1397
1398
  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);
1399
  kwsys_stl::string::size_type pos = 0;
1400
  // first convert all of the slashes
1401
  while((pos = ret.find('/', pos)) != kwsys_stl::string::npos)
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
    {
    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;
      }
    }
1423
  while((pos = ret.find("\\\\", pos)) != kwsys_stl::string::npos)
1424
1425
1426
1427
1428
    {
    ret.erase(pos, 1);
    }
  // now double quote the path if it has spaces in it
  // and is not already double quoted
1429
  if(ret.find(' ') != kwsys_stl::string::npos
1430
1431
     && ret[0] != '\"')
    {
Bill Hoffman's avatar
Bill Hoffman committed
1432
1433
    ret.insert(static_cast<kwsys_stl::string::size_type>(0),
               static_cast<kwsys_stl::string::size_type>(1), '\"');
1434
    ret.append(1, '\"');
1435
1436
1437
1438
1439
    }
  return ret;
}

bool SystemTools::CopyFileIfDifferent(const char* source,
1440
                                      const char* destination)
1441
1442
1443
{
  if(SystemTools::FilesDiffer(source, destination))
    {
1444
    return SystemTools::CopyFileAlways(source, destination);
1445
    }
1446
  return true;
1447
1448
}

1449
1450
#define KWSYS_ST_BUFFER 4096

1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
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__)
1477
1478
1479
1480
  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));
1481
#else
1482
1483
  kwsys_ios::ifstream finSource(source);
  kwsys_ios::ifstream finDestination(destination);
1484
1485
1486
1487
1488
1489
#endif
  if(!finSource || !finDestination)
    {
    return true;
    }

1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
  // Compare the files a block at a time.
  char source_buf[KWSYS_ST_BUFFER];
  char dest_buf[KWSYS_ST_BUFFER];
  long nleft = statSource.st_size;
  while(nleft > 0)
    {
    // Read a block from each file.
    long nnext = (nleft > KWSYS_ST_BUFFER)? KWSYS_ST_BUFFER : nleft;
    finSource.read(source_buf, nnext);
    finDestination.read(dest_buf, nnext);
1500

1501
1502
1503
1504
1505
1506
    // If either failed to read assume they are different.
    if(static_cast<long>(finSource.gcount()) != nnext ||
       static_cast<long>(finDestination.gcount()) != nnext)
      {
      return true;
      }
1507

1508
1509
1510
1511
1512
    // If this block differs the file differs.
    if(memcmp((const void*)source_buf, (const void*)dest_buf, nnext) != 0)
      {
      return true;
      }
1513

1514
1515
1516
    // Update the byte count remaining.
    nleft -= nnext;
    }
1517

1518
1519
  // No differences found.
  return false;
1520
1521
1522
1523
1524
1525
1526
1527
}


/**
 * Copy a file named by "source" to the file named by "destination".
 */
bool SystemTools::CopyFileAlways(const char* source, const char* destination)
{
1528
1529
1530
1531
1532
  // If files are the same do not copy
  if ( SystemTools::SameFile(source, destination) )
    {
    return true;
    }
1533
1534
1535
1536

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

1537
1538
1539
1540
1541
1542
  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.

1543
  kwsys_stl::string new_destination;
1544
1545
1546
1547
1548
1549
  if(SystemTools::FileExists(destination) &&
     SystemTools::FileIsDirectory(destination))
    {
    new_destination = destination;
    SystemTools::ConvertToUnixSlashes(new_destination);
    new_destination += '/';
1550
    kwsys_stl::string source_name = source;
1551
1552
1553
1554
1555
1556
    new_destination += SystemTools::GetFilenameName(source_name);
    destination = new_destination.c_str();
    }

  // Create destination directory

1557
  kwsys_stl::string destination_dir = destination;
1558
1559
1560
1561
1562
1563
  destination_dir = SystemTools::GetFilenamePath(destination_dir);
  SystemTools::MakeDirectory(destination_dir.c_str());

  // Open files

#if defined(_WIN32) || defined(__CYGWIN__)
1564
1565
  kwsys_ios::ifstream fin(source, 
                    kwsys_ios::ios::binary | kwsys_ios::ios::in);
1566
#else
1567
  kwsys_ios::ifstream fin(source);
1568
1569
1570
1571
1572
#endif
  if(!fin)
    {
    return false;
    }
1573
1574
1575
1576
1577
1578
 
  // 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);
1579

1580
#if defined(_WIN32) || defined(__CYGWIN__)
1581
1582
  kwsys_ios::ofstream fout(destination, 
                     kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc);
1583
#else
1584
1585
  kwsys_ios::ofstream fout(destination, 
                     kwsys_ios::ios::out | kwsys_ios::ios::trunc);
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
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
#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;
    }